Monday, August 3, 2009

Default parameters in c# 4

I just read about a very cool feature of "default parameter" in a webblog of a microsoft employee.I just want that others should also be aware of this feature so,I am included this in my post also.

Presently in c# 3.5 we all are just using the function overloading in order to provide the default or optional parameter functionality.e.g

public class oldclass
{
public string A{ get; set; }
public string B{ get; set; }
public string C{ get; set; }

public oldclass(string a)
{
A= a;
B= "B";
C= string.Empty;
}
public oldclass(string a, string b)
{
A= a;
B= b;
C= string.Empty;

}
public oldclass(string a, string b, string c)
{
A= a;
B= b;
C= c;
}
}
But now in c# 4 what we do is:-
public class newclass
{
public string A{ get; set; }
public string B{ get; set; }
public string C{ get; set; }

public newclass(string a, string b="B", string c=string.Empty)
{
A= a;
B= b;
C= c;
}
}
if we initialize constructor using-> new newclass("A");
then values for A="A",B="B"and C="".

So,Its quite cool to include this feature in c# 4 so that now,we don't have to use function overloading for getting functionality of optional parameters.

No comments:

Post a Comment