Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference in the behavior of optionalAttribute (used to declare an optional parameter) in VS 2010 vs VS 2008

Tags:

c#

.net

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?

like image 303
Mcgadiya Avatar asked Mar 09 '11 21:03

Mcgadiya


2 Answers

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#.

like image 80
vlad Avatar answered Sep 22 '22 18:09

vlad


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

like image 33
Davide Piras Avatar answered Sep 20 '22 18:09

Davide Piras