25 Aug 2009

C# 4.0 adds a bunch of new features, amongst which there is the Optional Parameters. If you don’t know about them and their drawbacks, please read this.

So, using this new syntax, you can specify so of the parameters to be optional, and have a default value in case they are not specified. Did you know that this applies to delegates too?

Here’s a simple delegate type declaration:

delegate void PrintName(String name = "Philippe");

Given this delegate type, you could think that any method receiving an optional String parameter and returning void would fit. Actually, it’s not the case. Any method receiving a String parameter and returning void will fit. If the parameter is not given when invoking the delegate, the optional value of the parameter will be used.

Here is a working example:

static void PrintToScreen(String name)
{
    Console.WriteLine("Hello in console from {0}", name);
}

static void Main(string[] args)
{
    PrintName p = OptionalsParametersOnDelegates.PrintToScreen;

    p();
}

This code will call the methods PrintToScreen with “Philippe” as argument for the name parameter. The delegate instance p can also be called with any String argument, which will be passed to the methods in the delegate invocation list.

Now, what happens if the method PrintToScreen also has an optional argument?

static void PrintToScreen(String name = "Bill")
{
    Console.WriteLine("Hello in console from {0}", name);
}

Making the name parameter optional and giving it a default value will not change the output of the previous code. It’s actually quite easy to explain: when the delegate instance is called with no parameter, the methods in the invocation list are called with the default value of parameter defined in the delegate type, in this case “Philippe”. If it is called with an argument, then the argument is passed along to the methods in the invocation list.



blog comments powered by Disqus