C# Tips & Tricks #30 – Optional and Named Parameters

Optional parameters and named Parameters is one of the new features that was introduced in in C# 4.0. It provides the ability to define a parameter for a function with some default value.

Visual Basic was one of the languages which still has the optional parameters and this is newly introduced in C# 4.0 .

Optional and Named Parameters

When the 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 , then 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 feature of this is that the Visual Studio 2010’s shows the parameter info as option with its Intellisense .

Optional and Named Parameters

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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...