What Are the Differences Between Delegates and Events

What are the differences between delegates and events?

An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.

What is the difference between delegate and event in C#?

I have an article on pretty much exactly

In brief, you can think of an event as being a bit like a property - but instead of having get/set operations, it has add/remove. The value being added/removed is always a delegate reference.

Delegates themselves support operations of:

  • Combine (chain multiple delegate instances together)
  • Remove (split them up again)
  • Invoke (synchronous or asynchronous)
  • Various things to do with finding out the target, invocation list etc

Note that delegates themselves are immutable, so combine/remove operations return a new delegate instance rather than modifying the existing ones.

Difference between events and delegates and its respective applications

From the technical standpoint, other answers have addressed the differences.

From a semantics perspective, events are actions raised by an object when certain conditions are met. For example, my Stock class has a property called Limit, and it raises an event when the stock prices reaches the Limit. This notification is done via an event. Whether anyone actually cares about this event and subscribes to it is beyond the concern of the owner class.

A delegate is a more generic term to describe a construct similar to a pointer in C/C++ terms. All delegates in .Net are multicast delegates. From a semantics perspective, they are generally used as a kind of input. In particular, they are a perfect way to implement the Strategy Pattern. For example, if I want to sort a List of objects, I can provide a Comparator strategy to the method to tell the implementation how to compare two objects.

I have used the two methods in production code. Tons of my data objects notify when certain properties are met. Most basic example, whenever a property changes, a PropertyChanged event is raised (see INotifyPropertyChanged interface). I have used delegates in code to provide different strategies of turning certain objects into string. This particular example was a glorified ToString() list of implementations for a particular object type to display it to users.

What is the relationship between delegates and events?

Short answer: see my article on the topic. Longer answer:

Events are a pattern on top of delegates. They're an implementation of the publisher/subscriber pattern (aka observer pattern), using delegates as the means of representing a subscription.

Whenever you see something like:

public event EventHandler Foo;

you should instead think of two methods:

public void AddFooHandler(EventHandler handler) { ... }
public void RemoveFooHandler(EventHandler handler) { ... }

All that a client from the outside can do is subscribe and unsubscribe. In particular, the client cannot raise the event themselves (without a separate method being provided for that purpose) nor can they "replace" or remove other subscriptions.

C# // Why use events and/or delegates?

Difference between delegates and events

So what’s really the difference between delegates and events other than the sugar coated syntax of events. The main difference is that event provides one more level of encapsulation over delegates.
So when we pass delegates it’s naked and the destination / subscriber can modify the delegate. When we use events the destination can only listen to it.

Summarizing Use of delegates

There are 6 important uses of delegates:-
1. Abstract and encapsulate a method (Anonymous invocation)
This is the most important use of delegates; it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods. In the previous section we have shown a simple example of a maths class. Later addition of new algorithm functions does not affect the UI code.

  1. Callback mechanismMany times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

  2. Asynchronous processingBy using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously. In our previous section we have explained the same in detail.

  3. Multicasting - Sequential processing Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate. This is already explained in the multicast example shown above.

  4. Events - Publisher subscriber modelWe can use events to create a pure publisher / subscriber model.

C# Event Implementation Fundamentals, Best Practices and Conventions

6 important uses of Delegates and Events

What is the difference between a delegate type and eventhandler type?

Here is my summary (please correct me if I'm wrong):

  • delegate is a pointer to a method (instance\static)

  • eventHandler is a delegate with a specific signature (sender, eventArgs)

  • event is an abstraction of accessing a delegate of any type, but it's usually an eventHandler by convention

    //We declare delegates as a new type outside of any class scope (can be also inside?)

    public delegate retType TypeName (params...)

    //Here we assign

    public TypeName concreteDeleagteName = new TypeName (specificMethodName);

    //Declaring event
    //a. taken from http://stackoverflow.com/questions/2923952/explicit-event-add-remove-misunderstood

    private EventHandler _explicitEvent;
    public event EventHandler ExplicitEvent
    {
    add
    {
    if (_explicitEvent == null) timer.Start();
    _explicitEvent += value;
    }
    remove
    {
    _explicitEvent -= value;
    if (_explicitEvent == null) timer.Stop();
    }
    }

    //or: b.auto event - the compiler creates a "hidden" delegate which is bounded to this event
    public event TypeName eventName;

I want to recommend the great article Event Handling in .NET Using C#.

So we can only attach (eventName):

eventName += new TypeName (specificMethodName);

Which is equivalent to (_eventName is a delegate\eventHandler):

_eventName += new TypeName (specificMethodName);

Events, Delegates vs Actions T

Action<T> is just an easy generic way to use delegates. It's equivalent to delegate MyDelegate(T arg)
It was added to save you some typing and it really saves the reader a LOT of hassle when trying to figure out what your delegate uses as parameters.

The event keyword has special meaning. It prevents this delegate from being triggered outside of the class. See this excellent answer for a discussion of why event is important and when you would use it (or not).

I don't understand the difference between pure delegate and event fields

Delegates and events are related concepts, but they are not the same thing. The term "delegate" tends to have two meanings (often glossed over):

  • A delegate type which is similar to a single method interface. (There are significant differences, but that's a reasonable starting point.)
  • An instance of that type, often created via a method group, such that when the delegate is "invoked", the method is called.

An event is neither of those. It's a kind of member in a type - a pair of add/remove methods, taking a delegate to subscribe to or unsubscribe from the event. The add and remove methods are used when you use foo.SomeEvent += handler; or foo.SomeEvent -= handler;.

This is very similar to how a property is really a pair of get/set methods (or possibly just one of the two).

When you declare a field-like event like this:

public event TickHandler Tick;

the compiler adds members to your class which are somewhat like this:

private TickHandler tick;

public event TickHandler
{
add { tick += value; }
remove { tick -= value; }
}

It's a bit more complicated than that, but that's the basic idea - it's a simple implementation of the event, just like an automatically implemented property. From inside the class, you can access the backing field, whereas outside the class you'll always end up just using the event.

Personally I think it's a pity that the declaration of a field-like event looks so much like a field of a delegate type - it leads to some of the misleading (IMO) statements found in some of the answers, as if the event keyword "modifies" a field declaration - when actually it means you're declaring something entirely different. I think it would have been clearer if field-like events looked more like automatically-implemented properties, e.g.

// Not real C#, but I wish it were...
public event TickHandler Tick { add; remove; }

I have a whole article going into rather more detail, which you may find useful.



Related Topics



Leave a reply



Submit