17

MSDN's VS2010 Named and Optional Arguments (C# Programming Guide) tells us about optional parameters in C#, showing code like I'd expect:

public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10) 

Ok, but it also says:

You can also declare optional parameters by using the .NET OptionalAttribute class. OptionalAttribute parameters do not require a default value.

I read MSDN's OptionalAttribute page, and done searches online (which shows lots of people claiming OptionalAttribute parameters can't be consumed by C# -- I'm guessing these comments were made before C# 4?), but I can't find the answer to two questions:

If I use OptionalAttribute to define a C# parameter as optional:

  1. what value will be used if I call that method and don't specify that parameter's value?
  2. will that value be evaluated at compile time or runtime?
2
  • Run it in debug and check it's value. I would suspect null. Commented Aug 5, 2010 at 15:18
  • Well, I'd suspect default(T) which is null or zero. Commented Aug 5, 2010 at 15:21

1 Answer 1

13

The rules are this:

Note that in the case of everything except parameters of type object, it's the equivalent of default(T).

I was a little surprised, as the C# 4.0 specification didn't indicate what the outcome would be, and I'd expect it to be there.

Also (as indicated by Scott Rippey in the comments), this is evaluated at compile-time, this is not a run-time operation, meaning that if you have calls to this method in other assemblies which are already deployed, and you change the optional value, the default passed to the method will not change unless you compile everything that makes the call against the method in the assembly.

Sign up to request clarification or add additional context in comments.

2 Comments

You should also mention that this is evaluated at compile time. The compiler actually inserts the default values into the calling code when compiling.
I think it's also worthwhile mentioning that when invoking a method by reflection, you pass in Type.Missing and the appropriate value will be inserted in the called method at run time. So it can be done at run time as well as compile time. (Reference: Type.Missing)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.