Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters on delegates doesn't work properly [duplicate]

Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}
like image 564
Stepan Benes Avatar asked Dec 04 '22 22:12

Stepan Benes


2 Answers

Optional parameters are for use on the calling side - not on what is effectively like a single-method-interface implementation. So for example, this should compile:

delegate void SimpleDelegate(bool x = true);

static void Main()
{
    SimpleDelegate x = Foo;
    x(); // Will print "True"
}

static void Foo(bool y)
{
    Console.WriteLine(y);
}
like image 106
Jon Skeet Avatar answered Dec 24 '22 09:12

Jon Skeet


What will happen test(false)? It will corrupt the stack, because signatures must match.

like image 24
Andrey Avatar answered Dec 24 '22 09:12

Andrey