Optional and Named Parameters in C# 4.0
Optional parameters and named Parameters are the new features in C# 4.0.It provides the ability to define a parameter for a function with some default value.
Visual Basic had the optional parameters and this is newly introduced in C# 4.0 .
When the Method / function is invoked, we can simply decline to supply a value and use the default value instead.
public void GetEmployeeDetails(int id = 1, string name = "senthil")
{
MessageBox.Show(name);
}
private void Form1_Load(object sender, EventArgs e)
{
GetEmployeeDetails(2);
}
The Method GetEmployeeDetails has a default value defined for the id and name .If we dont specify any parameters for the Method , it will take the default value,In the above example it prints “senthil”.
C# 4.0 provides another feature “Named Parameters” that enable us to call the method with the parameters in any order .
private void Form1_Load(object sender, EventArgs e)
{
GetEmployeeDetails(name: "kumar", id: 2);
}
The named parameters can work with any methods.
The other nice feature of this is that the Visual Studio 2010′s shows the parameter info as option with its Intellisense .
If you have 2 versions of the same method (Overloaded) , C# uses the method without the optional parameters .
Eg :
public void GetEmployeeDetails(int id, string name = "senthil")
{
MessageBox.Show(name);
}
public void GetEmployeeDetails(int id)
{
MessageBox.Show(id.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
GetEmployeeDetails(2);
}
In the above example , the GetEmployeeDetails(int id) that doesn’t have a optional parameters is given preference when a call with one parameter is made .
Note : The Optional Parameters must be placed after the required parameters else the C# compiler will show a compile time error.



[...] This post was mentioned on Twitter by . said: [...]