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.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...