6

Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}
Gabe
  • 84,912
  • 12
  • 139
  • 238
Stepan Benes
  • 121
  • 2
  • 3

3 Answers3

15

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);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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

Andrey
  • 59,039
  • 12
  • 119
  • 163
0

Try this way:

static int f(bool a)
{
  return 4;
}
Marco
  • 56,740
  • 14
  • 129
  • 152