Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I instantiate a new delegate or not?

I just realized I can add an event handler in two ways:

Consider an event handler like so:

private void MyEventHandler()
{}

Method 1: Instantiate a new delegate

MyObject.MyEvent += new Action(MyEventHandler);

Method 2: Add event handler without instantiating a new delegate

MyObject.MyEvent += MyEventHandler;

Is there any difference in between these two implementations that should be considered?

like image 443
Verax Avatar asked Jan 13 '11 03:01

Verax


People also ask

How do you instantiate a delegate?

Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.

Is delegates are not type safe?

Delegates are not type-safe. Delegate is a user-defined type. Only one method can be bound with one delegate object. Delegates can be used to implement callback notification.

Are delegates important in C#?

Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event. It doesn't care about the class of the object that it references. Delegates can also be used in “anonymous methods” invocation.


2 Answers

There is no difference, the generated IL is the same. The shorter form was introduced in .net/c# 2.0 as a convenience function, although Visual Studio still does the first form on Tab Completion.

See this question for some more info.

like image 113
Michael Stum Avatar answered Sep 28 '22 07:09

Michael Stum


I believe that while you can unsubscribe from the second, you'd not be able to unsubscribe from the first.

That would be a pretty important distinction. There is really nothing to be gained by wrapping it in an Action in any case.

update

Okay, I think I misunderstood what you were doing. If the event is declared as

public event Action MyEvent;

then the two subscriptions are equivalent, the second being shorthand for the first.

There are actually other ways to add event handlers:

MyObject.MyEvent += delegate { MyEventHandler(); };

MyObject.MyEvent += () => MyEventHandler();

In these cases, you would not be able to unsubscribe. In these examples, the delegates are calling the handler method, but usually when employing this method it is to avoid having to create separate handler methods -- the handler code goes right in the anonymous method.

like image 23
Jay Avatar answered Sep 28 '22 08:09

Jay