Using C# delegates with methods with optional parameters

PMichalak picture PMichalak · Apr 20, 2011 · Viewed 10.3k times · Source

Is there a chance to make this code work? Of course I can make second definition of Foo, but I think it'd be a little non-elegant ;)

delegate int Del(int x);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;
}

Answer

BoltClock picture BoltClock · Apr 20, 2011

Your delegate asks for exactly one parameter, while your Foo() method asks for at most two parameters (with the compiler providing default values for unspecified call arguments). Thus the method signatures are different, so you can't associate them this way.

To make it work, you need to either overload your Foo() method (like you said), or declare your delegate with the optional parameter:

delegate int Del(int x, int y = 123);

By the way, bear in mind that if you declare different default values in your delegate and the implementing method, the default value defined by the delegate type is used.

That is, this code prints 457 instead of 124 because d is Del:

delegate int Del(int x, int y = 456);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;

    Console.WriteLine(d(1));
}