Andrej Tozon's blog

In the Attic


Named & optional parameters in Silverlight 4

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. Needless to say, the default values will be used for those parameters which the calling function doesn’t provide. One thing to know is that optional parameter must always be declared after required parameters.

The following calls are all valid:

PositionWindow(true); // position and size set to defaults
PositionWindow(true, 100); // top position and size set to defaults
PositionWindow(true, 100, 200); // sizes set to defaults
PositionWindow(true, 100, 200, 600, 200); // all parameters provided

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, eh? The need for named and optional parameters may have come from the need to simplify COM automation, but they may prove just as useful in many other cases. But before you go start creating methods with tens of optional parameters, note that this is not the ultimate solution, and one thing worth noting is although the calls above look like they are passing the specified parameters only, the compiler in fact generates them with all parameters in place. This is how the Reflector sees that last batch of calls:

bool CS$0$0000 = true;
double CS$0$0001 = 600.0;
double CS$0$0002 = 200.0;
this.PositionWindow(CS$0$0000, 0.0, 0.0, CS$0$0001, CS$0$0002);
CS$0$0001 = 600.0;
CS$0$0002 = 200.0;
this.PositionWindow(true, 0.0, 0.0, CS$0$0001, CS$0$0002);
CS$0$0001 = 200.0;
CS$0$0002 = 600.0;
this.PositionWindow(true, 0.0, 0.0, CS$0$0002, CS$0$0001);
CS$0$0001 = 200.0;
CS$0$0002 = 600.0;
CS$0$0000 = true;
this.PositionWindow(CS$0$0000, 0.0, 0.0, CS$0$0002, CS$0$0001);

Potential architectural issues aside, I’m quite happy to see this feature come to Silverlight as well. How about you?