Introduction
C# 4.0 has introduced a number of interesting features which includes Optional Parameters, Default Values, and Named Parameters.
Functions with same name and different parameters (function overloading)
If we have a function,
public class Test
{
public void Print( int num1, num num2, num num3)
{
Console.WriteLine("{0},{1},{2}", num1, num2, num3);
}
}
This has three parameters.
How do we use it in the main function,
Test testClass = new Test();
testClass.Print(10, 12,14);
Suppose we require three different functions with same name and accepts different parameters (function overloading), to use in different scenario. The code will be,
public class Test
{
public void Print(int num3)
{
Print(10, 12, num3);
}
public void Print( int num2, int num3)
{
Print(10, num2, num3);
}
public void Print( int num1, double num2, string str)
{
Console.WriteLine("{0},{1},{2}", str, num1, num2);
}
}
Optional Parameters
You can provide optional values to the parameters. You can use these default values or give your own value, thereby can reduce the overhead of multiple functions.
Then the values can be given as,
public class Test
{
public Test(string someValue = "testValue")
//default values can be assigned for the constructor parameters also
{
}
public void Print(int num1= 5, int num2 = 10, int num3 = 15)
{
Console.WriteLine("{0},{1},{2}", num1, num2, num3);
}
}
Suppose we want the default value of only the last integer value then also we can call the function as,
Test testClass = new Test();
testClass.Print(10, 12);
Named Parameters
Suppose you want to change the third parameter value and have the default for second.
Can you do it like this,
testClass.Print(10, 12);
No the compiler misunderstand it to be num2. So we'll have to specify for which we use Named Parameters
testClass.Print(10, num3:12);
The new syntax '[parameter]:' is a very attractive achievement of C# 4.0
The convention with optional parameters is that optional parameters must come at the end of the list of method arguments. Hence, you specify all your required arguments in the method first and then list the optional arguments last just like we did above.