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");