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?