Nov 11

In VB.NET you have always been able to use optional parameters:

Sub Foo(ByVal p1 As String, Optional ByVal p2 As String = "default value")
End Sub

'Call to Foo with 1 of the 2 parameters is allowed
Foo("p1 value")

Now in C# 4.0 we get the same support:

void Foo(string p1, string p2 = "default value")
{
}

//Call to Foo with 1 of the 2 parameters is allowed
Foo("p1 value");


Although in C# now, we can still achieve the same using overloads. The example above just gives us another option. Equivalent C# 1.0 – 3.5 overload example:

void Foo(string p1)
{
     Foo(p1, "default value");
}

void Foo(string p1, string p2)
{
}

//Call to Foo with 1 of the 2 parameters is allowed
Foo("p1 value");

I don’t think this will make a great deal of difference to me (might make COM Interop easier). However I think when used in the right situations, it might make code more readable – for example replacing redundant overloads.

2 Responses to “C# 4.0 supports optional parameters”

  1. Alesha Gathje says:

    The RSS feed just isn’t in working order. Getting a 302 error.

  2. DalSoft says:

    Thanks for reporting it’s working now…

Leave a Reply

preload preload preload