14 January 2014

optional parameters in c#

C# optional parameters make method parameters optional; such parameters aren't required to pass while calling a method. Specified default value will be used when parameters not passed.

In this article let's understand C# optional parameters in detail by going through the below tutorial sections:

  1. What is the need for optional parameters?
  2. How to declare and use methods with optional parameters?
  3. Compiler role in getting optional parameters working
  4. Caveats you should be aware while working with optional parameter

What is the need for optional parameters?

Let's consider a C# code sample.

public class Customer
{
   public string Name {get;set;}
   public string MobileNumber{get;set;}
   public CustomerAddress Address {get;set;}
   public Customer(string name, sting mobileNumber)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;  
    }
   public Customer(string name, string mobileNumber, 
                   CustomerAddress address)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;
       this.Address = address;
    }
}
  • In the above Customer C# class example, there are two constructors, one is taking two parameters and other is taking three parameters.These are overloaded constructors, to provide the flexibility of creating Customer object without the need of CustomerAddress object being passed in.
  • Second constructor exist just for accepting the parameter CustomerAddress object, which is optional at the time of creating the instance of the Customer class.
  • Creating a second constructor just for accepting an optional parameter is maintenance overhead.

Using optional parameters, the second Customer class constructor can be avoided. So there will be less code in the class to achieve the same using optional parameter. But let's see how!

How to declare and use methods with optional parameters?

Using optional parameters in constructor methods, the Customer class code can re-written as below:

public class Customer
{
   public string Name {get;set;}
   public string MobileNumber{get;set;}
   public CustomerAddress Address {get;set;}
   
   public Customer(string name, string mobileNumber, 
                   CustomerAddress address = null)
    {
       this.Name = name;  
       this.MobileNumber = mobileNumber;
       this.Address = address;
    }
}
  • CustomerAddress is declared as optional parameter with the default value null.
    CustomerAddress address = null;
    The default value assigned to optional parameters using = sign in the method declaration.
  • Lines of code is reduced with optional parameter by removing the overloaded constructor and the Customer class code now looks less verbose!
  • Let's see how can we invoke methods declared with optional parameters.
  • //Not specifying optional parameter value
    Customer cust=new Customer("Arun""12345");

    //passing the optional parameter value
    cust=new Customer("Arun""12345",
                           new CustomerAddress());
    1. The first constructor method not passing value for the CustomerAddress explicitly which is a optional parameter. When no value passed for this optional parameter, the defined default value null is used.
    2. The second constructor method is passing value for the CustomerAddress. So the passed in value will be used.
  • Visual Studio intellisense showing the optional parameters:

    optional parameters in C# shown in Visual Studio

Compiler role in getting optional parameters working

After knowing how to use optional parameter, it's good to know how optional parameters works behind the scene.

  1. Let's consider the same Customer class constructor methods declared with optional parameters. When creating instance don't pass the value for optional parameter. When the code which is invoking the constructor is invoked, the C# compiler puts in the default value automatically for optional parameters which aren't passed.
  2. When you open the class in ILSPY assembly decompiler you can see that, parameter default value is explicitly put in by C# compiler. So at compile time only, the default value for the optional parameters will be binded.
  3. optional parameters in C# shown in ILSPY

Caveats you should be aware while working with optional parameter

As at compilation time, the optional parameters values will be explicitly binded just like named parameters you should be aware a situation.

Let's consider that you define the Customer class and related classes in one assembly and you are referring that assembly in another solution and creating Customer instance.

  1. First Scenario:Both the assemblies are compiled and deployed. Later modify the Customer class constructor assigning different default value instead of earlier null. Compile only that assembly and deploy.
    public Customer(string name, string mobileNumber, 
          CustomerAddress address = new CustomerAddress())
        {
           this.Name = name;  
           this.MobileNumber = mobileNumber;
           this.Address = address;
        }
    }
    Though the default value for optional parameter is changed, when other assembly code is executed, it will still pass the old optional parameter value which is null. Because that assembly is not yet compiled using latest assembly containing Customer class. Tricky interview question isn't?
  2. Second scenario:This time let's change the number of optional parameters with Customer class constructor by adding a new optional parameters, compile only that assembly & deploy it. This time the code will break throwing System.MissingMethodException runtime exception while trying to create an instance of the Customer class.

    This happens because the assembly which is referring Customer assembly, is not yet compiled and it's trying to create Customer instance by invoking 3 parameter constructor; Which doesn't exist in the latest Customer assembly and hence System.MissingMethodException is thrown. Another tricky interview question isn't?

1 comment:

  1. I have read so many articles about the blogger lovers but this article is
    in fact a nice post, keep it up.

    ReplyDelete