.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

C# 4 Optional Parameters

.NET

Category .NET  | Publication Date : 4/11/2010

One of the new language features coming in C# 4 is Optional Parameters. In large part, this is due to Microsoft’s plan of co-evolution with C# and VB.NET since VB.NET has had this feature for a while.

Consider a standard scenario with method overloading. In C# we’d have several methods with different signatures where we’re really just call the method with default values like in the following example:

public void myMethod(string param1, string param2)
{
    this.myMethod(param1, param2, true);
}
public void myMethod(string param1, string param2, bool param3)
{
    this.myMethod(param1, param2, param3, false);
}
public void myMethod(string param1, string param2, bool param3, bool param4)
{
    // Implementation here
}

With C# 4 we can now make the code more concise by only having to implement one method:

public void myMethod(string param1, string param2, bool param3 = true, bool param4 = false)
{
    // Implementation here
}

If consuming code is written using the minimum required parameters like this:

myObject.myMethod("first parameter", "second parameter");

The IL that the C# compiler will generate will actually be the equivalent of this:

myObject.myMethod("first parameter", "second parameter", true, false);

Unlike traditional method overloading, you have the ability to omit only the 3rd parameter in conjunction with the new Named Parameters language feature and write your code like this:

myObject.myMethod("first parameter", "second parameter", param4: true);

This will allow consuming code to only pass 3 arguments for succinctness but still invoke the appropriate overload since the IL generated in that instance will be equivalent to this:

myObject.myMethod("first parameter", "second parameter", true, true);


Related articles

Book: C# 4 Develop Windows applications with Visual Studio 2010

Visual Studio

Category Visual Studio  | Publication Date : 12/6/2010

C# 4 Optional parameters: Conflict Resolution

.NET

Category .NET  | Publication Date : 4/11/2010

C# 4 Named Parameters

.NET

Category .NET  | Publication Date : 4/11/2010