C# 4.0 : Optional Parameters
Days of creating multiple overloads to avoid parameters are gone. You no more have to create many methods and pass the default one there. C# 4.0 brings to us the concept of “optional” parameters.
How it works, let’s check it. Suppose you have a method like below,
public static class TestClass
{
public static void ParamMethod(string Name, double Salary,
string Department, int Age = 30)
{
Console.WriteLine("Name = {0}", Name);
Console.WriteLine("Age = {0}", Age);
Console.WriteLine("Salary = {0}", Salary);
Console.WriteLine("Department = {0}", Department);
}
}
Here you have mentioned the default value using “=” for the parameter “Age”.
Rule!!! You always have to put optional parameters after the “non-optional” parameters.
Now if you write the below code and call the method ParamMethod, you can omit the “optional parameter” Age.
class Program
{
static void Main(string[] args)
{
TestClass.ParamMethod("Wriju", 1000.00, "Software");
}
}
Will give you the below output,
Name = Wriju Age = 30 Salary = 1000 Department = Software |
Namoskar!!!
Comments
Anonymous
February 27, 2009
PingBack from http://www.anith.com/?p=14163Anonymous
May 21, 2009
"Days of creating multiple overloads to avoid parameters are gone." Not yet :) but as soon as 4.0 comes out they will be, it just doens't feel right to me when CTPs/Betas are referred to as being ready and available for use.