Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 3.5 Optional and DefaultValue for parameters

Tags:

I am using C# .net 3.5 to build an application. I have been working with optional parameter attributes in .net 4.0 with no problems. I did notice that with 3.5 there is the option (workaround) to add the following attributes to your method like so:

    public static void MethodName(string name, [Optional][DefaultValue(null)]string placeHolder)
    {

    }

Even though I have added the attributes to the method, if I try and call it like so:

     MethodName("test");

The compiler will complain that it is looking for two parameters instead of one. Is it actually possible to do this using C# .net 3.5? Am I doing something wrong?

like image 280
Deano Avatar asked Feb 25 '11 10:02

Deano


1 Answers

Optional parameters are C# 4.0 language feature so it doesn't matter which framework you are targeting, but you have to compile it using VS 2010 or newer.

Use this syntax in VS 2010 or newer:

public static void MethodName(string name, string placeHolder = null)
{
    // body
}

Or this in older one:

public static void MethodName(string name, string placeHolder)
{
    // body
}

public static void MethodName(string name)
{
    MethodName(name, null);
}
like image 74
rotman Avatar answered Sep 19 '22 09:09

rotman