C# 4.0 New Features: Optional Parameters in Methods

Microsoft has provided several new features in .Net 4.0 and among them one which i found a very useful and handy is that now instead of making overloaded methods developer can just make a single method and make the parameters as optional.

Following OOPs people used to write overloaded methods for handling multiple parameters in different way. Lets suppose you have a method named Execute() and following are the overloaded methods.


void Execute(int a){}
void Execute(int a, int b){}
void Execute(int a, int b, int c){}

Using .Net framework 4.0 you dont need to create multiple overloaded methods and you just have to create one as follows.


void Execute(int a, int optionalB = 0, int optionalC = 0)
{

}

And it can be called as follows.


Execute(1);
Execute(1,2);
Execute(1,2,3);

We can also pass the parameters in different orders considering the same method as follows.


Execute(optionalB: 2, optionalC: 3, a:1);

You only need to denote the parameter name followed with a colon and the framework automatically sets the value to that order parameter have in the method signature.