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.

Leave a Reply

preload preload preload