Tuesday, May 3, 2011

Simple question on anonymous method signatures and event handlers

So, probably a simple question with a simple answer, but I don't know what it is and I am curious :). Why does the compiler allow me to do something like this?

button1.Click += delegate { someFlag = true; };

(I can only use .NET 2.0, so no lamdas, but the same concept)

I cannot however do this:

button1.Click += MyDelegateMethod

// snip

// compile error, signature does not match the signature of System.EventHandler.
private void MyDelegateMethod( )
{ 

}

I would expect that I would have to declare my anonymous method as:

delegate(object sender, EventArgs e) { someFlag = true; };

I don't understand why it is ok for an anonymous method, but not ok when I write the full method itself. Anyone?

From stackoverflow
  • The compiler can figure out that your anonymous delegate is of the same type as the button Click delegate but that you do not need to use the event arguments.

    When you specify an actual method though, the compiler "sees" that you are pointing to a delegate with the wrong signature and therefore won't compile.

    Ed Swangren : "Compiler Magic", that's what I figured :)
  • As you can see you are using delegate { ... } and not delegate() { ... } which will allow C# to do the work for you.

    Ed Swangren : Yes, good point. I assumed that it was the same. You know what they say about making -ass-umptions...

0 comments:

Post a Comment