Yesterday while I was doing my work, suddenly came into stuck up in method where I wanna use some parameters and some not. So I searched trough our total search provider and came into notice about new features in c# 4.0, which helped me quiet in resolving my problem. So I think its better to share my ideas with you guys.
I found 4 new features in c#
- Named & Optional Parameter
- Dynamic Support
- Variance
- COM interop
Today I am going to blog on the first feature.
Named & Optional parameter
Named parameter is a way to provide an parameter to the method using the name of the corresponding parameter instead of its position in the parameter list.
Optional parameters allows you to give a method parameter a default value so that you do not have to specify it every time you call the method. This comes very useful when you have overloaded methods that are chained together.
Optional Parameter
I will explain this with a simple addition method where we have to pass 2 or 3 parameters to the ADD() method. For this to be done we traditionally go for method overloading.
For example:-
public int ADD( int a, int b);
public int ADD(int a, int b, int c);
public int ADD(int a, int b, int c, int d);
But when I saw this feature its much simpler and found a replacement of method overloading. By using Optional Parameter you can Pass default values to the method signature.
for eg:-
public int ADD(int a, int b, int c=0, int d=0);
Here we have passed default values to both c and d. So that you can call ur ADD() method like this any where.
ie for eg:-
ADD(20, 30); //20+30+0+0
ADD(10,50,60); //10+50+60+0
Named Parameter
Let us think that we have a situation where we are creating an account of an user with the method named "Account()" which has a non-optional parameter "Name" and two optional parameters "Address" & "Age". Here in some scenario you want to pass only the "Name" and "Age", how can you pass? Just think on it.
public void Account(string name, string address ="abc", int age=0);
Are you thinking of calling the method with an empty string or null value to the "Address" parameter? Oh, not really. There comes the another new feature of C# 4.0 called as "Named Parameter". Using this you can call the method with proper name resolution or even you can change the position of the parameter while calling the method. Have a look into the following code example:
Account("Febin", age:23);
Account(address: "India", name: "Febin");
First example shows calling the method without the middle parameter "Address" and the second example demonstrates calling the same method after changing the position of the parameter in the parameter list using the name of the parameter.
By this way you can create a single method with Named & Optional Parameter instead of overloading it for several times and use it everywhere you need.