Coding Geek

A blog by Nadeem Iqbal

Silverlight 4.0 Optional & Named Parameters

Named & optional parameters are a new C# language feature coming up with .NET FX 4.0 and guess what… it’s in Silverlight 4 as well!

Optional parameters will come very useful when defining complex APIs where you would usually have to provide several overloads for the same method for it to make sense to wide variety of usages. Let’s take a look at this basic example:

public void PositionWindow(bool isTopMost, double left = 0, double top = 0, double width = 800, double height = 600)

{
Window window = Application.Current.MainWindow;
window.TopMost = isTopMost;
window.Left = left;
window.Top = top;
window.Width = width;
window.Height = height;
}

 isTopMost is the only parameter that’s required, all other parameter specify their default value, which makes them optional.

 But what if you wanted to provide the size only and leave the position to be set to defaults? Enter named parameters. The same method above can be called also with:

PositionWindow(isTopMost:true, width: 600, height: 200); // named parameters

PositionWindow(true, width: 600, height: 200); // naming is optional when positioned right
PositionWindow(true, height: 200, width: 600); // order doesn't matter
PositionWindow(height: 200, width: 600, isTopMost: true); // ... even with the required parameters

 Simple ... Cheers:)

Comments

AndrewSeven said:

These can be useful features, but they are not without drawbacks.

With optional parameters, the default values get copied into the calling assembly.

With named parameters, the name of the parameter almost becomes part of the interface. Correcting a spelling error in a parameter name will break callers.

# September 3, 2010 2:12 PM

niqbal said:

AndrewSeven.. thanks for feedback

# September 8, 2010 6:13 AM

willow said:

Bravo, me parece esto el pensamiento admirable  

http://eru1.myftp.biz/  

williamsburg

# August 19, 2011 8:53 AM

AnnaFrakloop said:

Good article to my mind. Keep writing this way!

Anna Frakloop

<a href="black-escort-london.com/">black escort london</a>

# November 6, 2011 5:18 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)