Assigning a delegate without an EventHandler signature - how does it work?

If I do this line:

EventHandler foobar = new EventHandler(fooMethod);

fooMethod must be a method with the following signature:

public void fooMethod(object obj, EventArgs args){}

It makes sense to me. However, this code works very well:

EventHandler foo = delegate { };

Like this? I would think that I need to do this:

EventHandler foo = delegate(object obj, EventArgs arg) { };

The above line works btw. I'm just confused about how I can assign an "empty" EventHandler delegate.

Thanks to everyone who can light me up!

+3
source share
1 answer

Anonymous methods (the way to create delegates through delegate { /* body */ }has two forms:

delegate (parameter list)
{
    // body
}

and

delegate
{
    // body
}

, out (IIRC - ref), . :

Func<int> foo = delegate { return 5; };

, . , , , :

new Thread(delegate { Console.WriteLine("Error - ambiguous"); });
new Thread(delegate() { Console.WriteLine("Fine - ThreadStart"); });
new Thread(delegate(object state) {
    Console.WriteLine("Fine - ParameterizedThreadStart");
});
+4

All Articles