C# 4.0 optional parameter and named arguments

17. January 2011 00:25 by Mahmoud Farhat in C#, C#, C#, C#, C#, C#, C#, C#  //  Tags:   //   Comments (0)

C# now supporting optional parameter in methods, constructors, indexers and this is new feature coming in C# 4.0 with additional feature named arguments

- Optional parameter:

The optional parameters idea is that the arguments on a method may have default values and therefore it is unnecessary to pass those arguments in a method if you are willing to accept those default values.  And this may be helping you when you are going to overload methods several times.

Example:

public static void UserInfo(string name, int age, string country = "Egypt”) {
            Console.Write(" Name:{0} \n Age:{1} \n Country:{2}",name,age,country);
        }

In the method above we set a default value in country, which means it can now be used optionally by caller of the method

UserInfo(“Mahmoud”,30); 

The country is not specified and this means you are accept to take the default value and then you can handle you work flow as you.

Output:
Name:Mahmoud
Age:30
Country:Egypt

or you can override the country by passing country name  

UserInfo(“Mahmoud”,30,”USA”); 

Output:
Name:Mahmoud
Age:30
Country:USA

- Named parameters

Sometime you have multiple optional parameters

public static void UserInfo(string name, int age, string country = "Egypt", _

       string city = "Cairo"){}

And the question here how do you specify the value of city without specify the value of county??!!

We can do that by “Named Parameter”, and this means that The parameter for each argument can be specified by parameter name

UserInfo("Mahmoud",30,city:"Alex");


Note:

The optional parameters must come at the end of the list of method arguments. And you have to specify all your required arguments in the method first and then list the optional arguments last just like above samples.