Adding method to event by casting delegate?

I come from a Java background and am currently learning c#.

I understand that when one wants to subscribe a method to a event, one does it like the following:

button.Click += HandleClick;

void HandleClick (object sender, EventArgs e) {
   button.Text = string.Format (count++ + " clicks!"); 
}

However, one can seem to write this like the following to:

button.Click += delegate {button.Text = string.Format (count++ + " clicks!");};

Are we casting the method to a delegate? I thought the event wants a method to be subscribed to it? What exactly is happing above?

Jon Skeet
people
quotationmark

Are we casting the method to a delegate?

Well, you're not casting - but you're using a method group conversion to convert a method name into a delegate.

I thought the event wants a method to be subscribed to it?

No, an event needs a delegate to subscribe to it (or unsubscribe from it). You can create a delegate instance from a method, either with the code you've given or more explicitly:

button.Click += new EventHandler(HandleClick);

Or even separate the two:

EventHandler handler = HandleClick; // Method group conversion
button.Click += handler;            // Event subscription

... or you can create a delegate instance from an anonymous function (either an anonymous method or a lambda expression).

See my article on delegates and events for more information.

people

See more on this question at Stackoverflow