views:

58

answers:

1

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 attribute?
  2. will that value be evaluated at compile time or runtime?
+1  A: 

The rules are this:

  • For parameters of type object, Type.Missing is passed.
  • For other reference types, null is passed.
  • For value types, the default of the value type is passed.
    • For Nullable<T> this means that you will get a Nullable<T> instance which is equal to null (the HasValue property will return false)

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.

casperOne