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));
}