A simple C# method with an optional parameter declared using the OptionalAttribute as
namespace ClassLibrary11
{
public class Class1
{
public int Foo(int a, int b, [Optional] int c)
{
return a + b + c;
}
}
}
On VS 2010. obj.Foo(3,4)
outputs 7
as expected. But not on VS 2008 or before unless there is some default value is provided using DefaultParameterValue Attribute. So a call to Foo(3,4)
on VS2008 or before results into an error:
Object of type 'System.Reflection.Missing' cannot be converted to type 'System.Double'
On both VS 2008 and VS 2010, if reflection is used to invoke method Foo, then it throws the same error if the default value is not provided for the optional parameter.
ClassLibrary11.Class1 cls = new ClassLibrary11.Class1();
MethodInfo mi = typeof(ClassLibrary11.Class1).GetMethod("Foo");
Object[] objarr = new Object[] {1,2, Missing.Value};
Object res = mi.Invoke(cls, objarr);
So the question is:
So how is that VS 2010 compiler takes care of assigning the default value to the optional parameter but the framework 4.0 does not via reflection?
simply put, it's because C# 3.5 doesn't support optional parameters. As per MSDN,
Note that the DefaultParameterValueAttribute does not add support for default parameters to languages that do not support this feature. For example, if you use the DefaultParameterValueAttribute with a method written in C#, which does not support default parameters, you cannot use the default parameter when calling the method from C#.
Optional parameters have been introduced with .NET 4.0 in C#, I am not sure what you are building with VS 2008 targetting an older framework, but I would say you should use them only in VS 2010 and .NET 4.0 Named and Optional Arguments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With