Monday, November 2, 2009
C# 4.0 New Features part 1: Optional and Named Parameters
One of the cool new features of C# 4.0 is the abillity to use optional and named parameters. Although this is not something that changes our way of programming, it is a very handy feature though!
Optional Parameters
Writing an optional parameter is very simple:
public string HelloWorld (string message = "Hello World")
{
return message;
}
This makes it possible to call the function with HelloWorld() and HelloWorld("My message!"). Although this is no Major framework change, it will save you a lot of overloads !
Named parameters
Normally you always have to provide parameters in the order in which they are defined. This is very irritating when you have a large amount of parameters to specify in a function call. Aspecially when you change the signature of the function or procedure, you will have to change all calls to it also. Further more, you have to have the same order for the paramaters as defined in the signature.
Now in C# 4.0 Microsoft introduces a solution for this problem too: Named parameters
Example:
public string Combine(int x, string y)
{
return string.format("{0} {1}",y,x);
}
Normaly you would have to call this function like this: Combine(125,"SomeStreet"). With the new named parameters we are not tied to the order of the parameters anymore.
We simply specify the parameter we're setting: Combine(X:"SomeStreet",Y:125)
Easy comes, Easy goes !
It gets even more fun when you combine Optional and Named parameters.
Example:
public void DoThing(string param1 = "", string param2 = "", int param3 = 0)
{
//Do something usefull with the parameters.
}
In C# 4.0 you can call the method this way: DoThing(param2:"test") and nothing breaks !!!
Cool aint it ?
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment