.NET life

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

C# 4 Named Parameters

.NET

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

A new feature of C# 4 is the principle of named parameter.

Imagine a function that requests the last name and the first name of a person to view the whole:

public void SayHello(string Lastname, string Firstname)
{
    Console.WriteLine("Hello {0} {1}", Lastname, Firstname);
}

We can provide default values for parameters like this:

public void SayHello(string Lastname="HUGON", string Firstname="Jérôme")

These parameters become optional, imagine that we called the method like this:

myObject.SayHello();

Then she will display:

Hello HUGON Jérôme

Now we can give specified values other than the default ones using this syntax:

myObject.SayHello(Lastname:"DOE", Firstname:"John");

This will display:

Hello DOE John

One thing to know is that the mandatory parameters must be set first in the list of parameters, for example putting a mandatory parameter civility:

public void SayHello(string Civility, string Lastname="HUGON", string Firstname="Jérôme")

This time we can no longer call SayHello without parameters because there is no overload, we must specify the required parameter:

myObject.SayHello("Mr");


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 Optional Parameters

.NET

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