Click here to Skip to main content
11,480,031 members (65,124 online)
Click here to Skip to main content

An introduction to Optional Parameters - C#4.0

, 27 Oct 2010 CPOL 17.5K 68 7
Rate this:
Please Sign up or sign in to vote.
This article shows the benefits of using Optional Parameter

Introduction

C#4.0 has bring the new Optional Parameter in its collection to give developers the flexibility passing parameters at their discretion.

Background:

Consider the below example which is done in C#3.0

class Program
    {
        static void Main(string[] args)
        {
            WithoutNamedParameter(null,null); //Print default values
            WithoutNamedParameter("Some Name", null); //Print only default age
            WithoutNamedParameter(null, 25); //Print only default name
            WithoutNamedParameter("Some Name", 50); //Print the value passed
            
            Console.ReadKey(true);
        }

        private static void WithoutNamedParameter(string name, int? age)
        {
            string _name = "Default Name";
            int? _age = 18;

            //Check if name is empty or not and hence assign
            if (!string.IsNullOrEmpty(name)) _name = name;

            //Check if age is empty or not and hence assign
            if (age.HasValue) _age = age;

            Console.WriteLine(string.Format("{0},your age is {1}", _name, _age));
        }        
    }

In the WithoutNamedParameter method first we have assigned two default values to the two variables _name and age. Then we are checking, if the Calling function has assigned any value to the method parameters or not and depending on that, we are displaying the values.

Next have a look at the calling function. The method WithoutNamedParameter has been called four times with four different values. But the code looks pretty ugly.

Another option was to create four overloaded method to satisfy the requirement if the Empty or Null checking needs to be avoided which on the other hand was again a tedious job.

The new Optional Parameter, introduced with C#4.0 has a better look.

Optional Parameters

Consider the below program written in C#4.0

 class Program
    {
        static void Main(string[] args)
        {
            MethodWithOptionalParameters();//Print default values

            MethodWithOptionalParameters("Some Name");//Print only default age

            MethodWithOptionalParameters(Age: 25);//Ask to print only Name

            //Prints the values passed
            MethodWithOptionalParameters("Some Other Name", 20);

            Console.ReadKey(true);
        }

       private static void MethodWithOptionalParameters
                       (string Name = "Default Name", int Age = 18)
        {
           Console.WriteLine(string.Format("{0}, your age is {1}",Name,Age));
        }
    }

As can be observed that first of all in the new code we are no longer checking the Empty/Null values of the method parameters. Instead , we have assigned the default values to the method parameters.

Consider the First Calling Method. We are not at all passing any parameter. The complier will happily compile though (which was not the case in the earlier example as it would have reported the error No overload for method 'WithoutNamedParameter' takes '0' arguments.

The IL for the code is depicted below

3.jpg

Which indicates that the Optional Parameter is in the MSIL.

Consider the third Method call

MethodWithOptionalParameters(Age: 25);//Ask to print only Name

Here we are specifying the Age only which is a Named Parameter in this case and the complier will understand that and will do the favour./p>

The final output being

4.jpg

Conclusion:

In this short article we have seen how optional parameter help developers to avoid writing overloaded methods and rather helps in code reusability.

Comments on the topic are highly appreciated for the improvement of the topic.

Thanks for reading the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 1 Pin
Batzen28-Oct-10 2:53
memberBatzen28-Oct-10 2:53 
GeneralMy vote of 1 Pin
Volem28-Oct-10 0:35
memberVolem28-Oct-10 0:35 
GeneralMy vote of 1 Pin
SledgeHammer0127-Oct-10 10:18
memberSledgeHammer0127-Oct-10 10:18 
GeneralMy vote of 1 Pin
Argyle4Ever27-Oct-10 5:27
memberArgyle4Ever27-Oct-10 5:27 
GeneralMy vote of 2 Pin
Toli Cuturicu27-Oct-10 3:51
memberToli Cuturicu27-Oct-10 3:51 
GeneralMy vote of 1 Pin
Arun Jacob27-Oct-10 1:18
memberArun Jacob27-Oct-10 1:18 
GeneralMy vote of 1 Pin
M8ix26-Oct-10 19:40
memberM8ix26-Oct-10 19:40 
GeneralMy vote of 1 Pin
JF201526-Oct-10 19:16
memberJF201526-Oct-10 19:16 
GeneralRe: My vote of 1 Pin
Niladri_Biswas27-Oct-10 0:12
memberNiladri_Biswas27-Oct-10 0:12 
GeneralMy vote of 1 Pin
Keith Barrow26-Oct-10 8:08
memberKeith Barrow26-Oct-10 8:08 
GeneralMy vote of 1 Pin
Selvin26-Oct-10 5:44
memberSelvin26-Oct-10 5:44 
GeneralMy vote of 1 Pin
Nagy Vilmos26-Oct-10 3:29
memberNagy Vilmos26-Oct-10 3:29 
GeneralMy vote of 1 Pin
Seishin#26-Oct-10 2:59
memberSeishin#26-Oct-10 2:59 
Generalseriously, stop reqriting "begginers guide to c# 4.0"... Pin
Seishin#26-Oct-10 2:59
memberSeishin#26-Oct-10 2:59 
GeneralGood to see someone from HCL on CodeProject Pin
The Manoj Kumar25-Oct-10 18:06
memberThe Manoj Kumar25-Oct-10 18:06 
GeneralRe: Good to see someone from HCL on CodeProject Pin
Niladri_Biswas25-Oct-10 20:38
memberNiladri_Biswas25-Oct-10 20:38 
GeneralRe: Good to see someone from HCL on CodeProject Pin
The Manoj Kumar25-Oct-10 23:53
memberThe Manoj Kumar25-Oct-10 23:53 
GeneralRe: Good to see someone from HCL on CodeProject Pin
Niladri_Biswas26-Oct-10 1:20
memberNiladri_Biswas26-Oct-10 1:20 
GeneralMy vote of 5 Pin
moeinkiller200525-Oct-10 6:55
membermoeinkiller200525-Oct-10 6:55 
GeneralRe: My vote of 5 Pin
Niladri_Biswas25-Oct-10 20:39
memberNiladri_Biswas25-Oct-10 20:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 27 Oct 2010
Article Copyright 2010 by Niladri_Biswas
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid