C# 4.0 Feature - Optional Arguments

The feature that we are discussing today is called as “Optional Arguments”. Prior to C#4.0, whenever we need to pass optional parameters for a method, we used to use method overloading . For eg:
private int Add(int i)
{
return i + 2;
}

Now if the Add method wanted to accept two parameters then we used to write as follows
private int Add(int i, int j)
{
return i + j;
}

Now if the Add method wanted to accept two parameters then we used to write as follows
private int Add(int i, int j, int k)
{
return i + j + k;
}

Eventually we had to write three overloaded methods based on the number of parameters passed and invoke the method based on the parameters passed.
In C#4.0, we can rewrite the code by declaring parameters as optional as follows
private int Add(int i, int j = 1, int k = 0)
{
return i + j + k;
}

When invoking this method and need only one parameter to be passed use it as follows
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Add(2).ToString());
}

In this case the result will be show as 3 since for “i” we passed 2 , the default for “j” is 1 and the default for “k” is 0. If we were to pass 2 parameters it would be as follows
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Add(2, 3).ToString());
}

Now the result would be 5, since for “i” we passed 2, for “j” we passed 3 and the default for “k” is 0.

Hope this was cool feature. Please add your comments or suggestions.

Cheers!!!

Comments

Popular posts from this blog

Partition Function in SQL Server

WPF/E