Why does a delegate without parameters compile?

I am confused why this compiles:

private delegate int MyDelegate(int p1, int p2); private void testDelegate() { MyDelegate imp = delegate { return 1; }; } 

MyDelegate should be a pointer to a method that takes two int parameters and returns another int, right? Why am I allowed to assign a method that does not accept any parameters?

Interestingly, they do not compile (he complains about signature mismatches, as I expected)

  private void testDelegate() { // Missing param MyDelegate imp = delegate(int p1) { return 1; }; // Wrong return type MyDelegate imp2 = delegate(int p1, int p2) { return "String"; }; } 

Thanks for any help!

Ryan

+6
c # delegates
source share
2 answers

Well, in the first example, the compiler can easily see that no parameters are used, and replace several dummies.

It looks like a design decision, somewhere on the road, from the description - everything in .NET 1, through anonymous methods in .NET 2 for lambdas in .Net 3

+5
source share

Your first example is a short syntax if the delegate doesn't need parameters. If you need at least one of them, you need to provide them all, so the first part of the second example will not compile.

+6
source share

All Articles