Monday, February 20, 2012

How to Add Optional Parameters in C#

It Is introduced in C# 4.0 along with VS 2010. It used to increase the readability and maintainability of the code. 

                                                For Example:
public void CommonFunction(int _iAppID)
{
Console.WriteLine("Parameter a is: {0}", _iAppID);
}

You have create one function(CommonFunction) which accept only one parameter and it is called in so many places in your application. After some time your requirement has changed and you want to add one more parameter in the same method. Once you add new parameter, you have to pass the same parameters throughout the application which could not be easy task. Here’s the Optional parameter comes in to picture.

It is added at the end of the parameter list and have default values, If no argument is sent for that parameter, the default value is used. Default values must be constants.
public void CommonFunction(int a, int b = 4, string c = "James")
{
Console.WriteLine("Parameter a is: {0}", a);
Console.WriteLine("Parameter b is: {0}", b);
Console.WriteLine("Parameter c is: {0}", c);
}
Now, You can call this functions in three different ways as 
1.  CommonFunction(4);  
      // Output: Parameter a is: 4 
      // Output: Parameter b is: 4 
      // Output: Parameter c is: James

2.  CommonFunction(4,5);
        // Output: Parameter a is: 4
        // Output: Parameter b is: 5
        // Output: Parameter c is: James

3.    CommonFunction(4,5,"Veronica");
        // Output: Parameter a is: 4
        // Output: Parameter b is: 5
        // Output: Parameter c is: Veronica

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine