Luke Taylor
Luke Taylor

Reputation: 9599

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?

Upvotes: 0

Views: 98

Answers (2)

Servy
Servy

Reputation: 203822

The delegate keyword is creating a new anonymous method. A delegate is then (implicitly) created that refers to that anonymous method, and that delegate is added as one of the delegates for that event.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

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.

Upvotes: 3

Related Questions