C# 4.0 Optional and Named Parameters

C# 4.0 now supports the optional and named prameters. this feature was already there in VB.NET so it is a C# language enhancement.
consider the below class:

class Optional
{
public void DoOperation(string name = “hello”, int age = 4)
{
Console.Write(“Name {0}, Age {1}”, name, age.ToString());
}
}

you can notice that now we can specify default values for parameters “name” and “age”. so now when using the below code:

Optional optional = new Optional();
optional.DoOperation();

the default parameter values are passed to the method. and when we call the method as follows:

optional.DoOperation(“mohamad”);

then “name” will have its new value set, while “age” parameter will have its default value.

now the question is what if we want to call the method passing only the “age” parameter while giving the “name” parameter its default value? we cannot simpy do the following:

optional.DoOperation(2);

because this will give a compilation error since the compiler “understands” parameters by position and this means we are supplying an integer value to a string parameter. The solution is using Named Parameters. We can do the following:

optional.DoOperation(age:2);

by specifying the Parameter name we can ommit the first parameter and pass the second one only.

as you might have noticed, this feature will for sure result in much less method overloading that we used to do just to change the number of parameters of each overload!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s