Coding Geek

A blog by Nadeem Iqbal

September 2010 - Posts

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:)

More Posts