Difference between events and delegates and its respective applications [closed]
Asked Answered
P

10

111

I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which? What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

Placentation answered 19/2, 2009 at 1:11 Comment(3)
Yeah wrapping my head around the differences was really hard, they look the same and seem to do the same at first lookJauregui
See also this question.Freak
The difference between two events and delegates is a matter of fact, not opinion. The question asks for respective applications because they illustrate difference in the problems that the technologies solve. This also is not a matter of opinion because nobody asked which was best. No part of this question is a matter of opinion, and this statement is also not opinion. In my opinion. Did you get your badge?Belay
C
48

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.

Chokebore answered 19/2, 2009 at 1:50 Comment(5)
Maybe I'm missing something, but isn't an Event Handler a type of delegate?Oneiromancy
My answer addresses the questions Edit #1 and #2; differences from a usage perspective. For the purposes of this discussion, they are different, even though, from a technical standpoint, you are correct. Take a look at the other answers for technical differences.Chokebore
"All delegates in .Net are multicast delegates"? Even delegates that return values?Salvatoresalvay
Yes. For history, take a look at msdn.microsoft.com/en-us/magazine/cc301816.aspx. Check out: msdn.microsoft.com/en-us/library/system.delegate.aspx. If they return values, the value that is returned is the evalutation of last delegate in the chain.Chokebore
delegates are reference types that points to the event handlers defined in the subscriber class. In otherwords, the delegate is used as a link between the event (in the publisher) and the event handler defined in the subscriber. In an application, there will be multiple subscribers need to listen to an event, and in such scenarios delegates offer us an efficient way to link publisher and subscribers.Chlori
B
56

The keyword event is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows:

  • You can use event in an interface.
  • Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg public event).

As a matter of interest, you can apply + and - to multicast delegates, and this is the basis of the += and -= syntax for the combination assignment of delegates to events. These three snippets are equivalent:

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B + C;

Sample two, illustrating both direct assignment and combination assignment.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B;
A += C;

Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = null;
A += B;
A += C;

Like properties, events have a full syntax that no-one ever uses. This:

class myExample 
{
  internal EventHandler eh;

  public event EventHandler OnSubmit 
  { 
    add 
    {
      eh = Delegate.Combine(eh, value) as EventHandler;
    }
    remove
    {
      eh = Delegate.Remove(eh, value) as EventHandler;
    }
  }

  ...
}

...does exactly the same as this:

class myExample 
{
  public event EventHandler OnSubmit;
}

The add and remove methods are more conspicuous in the rather stilted syntax that VB.NET uses (no operator overloads).

Belay answered 19/2, 2009 at 1:56 Comment(3)
+ for "Invocation access to the multicast delegate is limited to the declaring class"- that to me is the key difference point between delegates and events.Autosuggestion
Another important difference (mentioned by itowlson below) is that one can't unsubscribe all event handlers by assigning to an event, but they could do that with a delegate. (By the way, yours was the most useful answer to me of all these).Numismatist
As handy as Google and stackoverflow might be, all this and more is available in mind-numbing detail in the C# language spec, publicly available at no charge from Microsoft. I know that on the face of it, god created the manual and Jon Skeet swallowed it, but there are other copies :)Belay
C
48

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.

Chokebore answered 19/2, 2009 at 1:50 Comment(5)
Maybe I'm missing something, but isn't an Event Handler a type of delegate?Oneiromancy
My answer addresses the questions Edit #1 and #2; differences from a usage perspective. For the purposes of this discussion, they are different, even though, from a technical standpoint, you are correct. Take a look at the other answers for technical differences.Chokebore
"All delegates in .Net are multicast delegates"? Even delegates that return values?Salvatoresalvay
Yes. For history, take a look at msdn.microsoft.com/en-us/magazine/cc301816.aspx. Check out: msdn.microsoft.com/en-us/library/system.delegate.aspx. If they return values, the value that is returned is the evalutation of last delegate in the chain.Chokebore
delegates are reference types that points to the event handlers defined in the subscriber class. In otherwords, the delegate is used as a link between the event (in the publisher) and the event handler defined in the subscriber. In an application, there will be multiple subscribers need to listen to an event, and in such scenarios delegates offer us an efficient way to link publisher and subscribers.Chlori
D
12

Events are syntactical sugar. They are delicious. When I see an event, I know what to do. When I see a delegate, I'm not so sure.

Combining events with interfaces (more sugar) makes for a mouth watering snack. Delegates and pure virtual abstract classes are much less appetizing.

Damning answered 19/2, 2009 at 1:29 Comment(2)
that's how I see it too. I want deeper and more sweet explanation :)Placentation
Too much sugar makes one fat, however... =PSchedule
C
6

Events are marked as such in the metadata. This allows things like the Windows Forms or ASP.NET designers to distinguish events from mere properties of delegate type, and provide appropriate support for them (specifically showing them on the Events tab of the Properties window).

Another difference from a property of delegate type is that users can only add and remove event handlers, whereas with a property of delegate type they can set the value:

someObj.SomeCallback = MyCallback;  // okay, replaces any existing callback
someObj.SomeEvent = MyHandler;  // not okay, must use += instead

This helps to isolate event subscribers: I can add my handler to an event, and you can add your handler to the same event, and you won't accidentally overwrite my handler.

Choline answered 19/2, 2009 at 1:48 Comment(0)
C
4

Edit#1 When would you use delegates over events and vs.versa? Please state your real world experience with both, say in the production code.

When I design my own APIs, I define delegates which are passed as parameters to methods, or to the constructors of classes:

  • So that a method can implement a simple 'template method' pattern (as e.g. the Predicate and Action delegates are passed to the .Net generic collection classes)
  • Or so that the class can do a 'callback' (typically a callback to a method of the class which created it).

These delegates are generally non-optional at run-time (i.e. mustn't be null).

I tend not to use events; but where I do use events, I use them for optionally signalling events to zero, one, or more clients that might be interested, i.e. when it makes sense that a class (e.g. the System.Windows.Form class) should exist and run whether or not any client has added an event handler to its event (e.g. the form's 'mouse down' event exists, but it's optional whether any external client is interested in installing an event handler onto that event).

Chef answered 19/2, 2009 at 2:30 Comment(0)
H
4

Although events are typically implemented with multicast delegates, there is no requirement that they be used in such fashion. If a class exposes event, that means the class exposes two methods. Their meanings are, in essence:

  1. Here's a delegate. Please invoke it when something interesting happens.
  2. Here's a delegate. You should destroy all reference to it as soon as convenient (and no longer call it).

The most common way for a class to handle an event it exposes is to define a multicast delegate, and add/remove any delegates that get passed to the above methods but there is no requirement that they work that way. Unfortunately, the event architecture fails to do some things that would have made alternative approaches much cleaner (e.g. have the subscription method return a MethodInvoker, which would be kept by the subscriber; to unsubscribe an event, simply invoke the returned method) so multicast delegates are by far the most common approach.

Hampshire answered 7/12, 2010 at 23:50 Comment(0)
A
4

to understand the differences you can look at this 2 examples

Exemple with Delegates (Action in this case that is a kind of delegate that doen't return value)

public class Animal
{
    public Action Run {get; set;}

    public void RaiseEvent()
    {
        if (Run != null)
        {
            Run();
        }
    }
}

to use the delegate you should do something like this

Animale animal= new Animal();
animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running") ;
animal.RaiseEvent();

this code works well but you could have some weak spots.

For example if I write this

animal.Run += () => Console.WriteLine("I'm running");
animal.Run += () => Console.WriteLine("I'm still running");
animal.Run = () => Console.WriteLine("I'm sleeping") ;

with the last line of code I had override the previous behaviors just with one missing + (I have used + instead of +=)

Another weak spot is that every class that use your Animal class can raise RaiseEvent just calling it animal.RaiseEvent().

To avoid this weak spots you can use events in c#.

Your Animal class will change in this way

public class ArgsSpecial :EventArgs
   {
        public ArgsSpecial (string val)
        {
            Operation=val;
        }

        public string Operation {get; set;}
   } 



 public class Animal
    {
       public event EventHandler<ArgsSpecial> Run = delegate{} //empty delegate. In this way you are sure that value is always != null because no one outside of the class can change it

       public void RaiseEvent()
       {  
          Run(this, new ArgsSpecial("Run faster"));
       }
    }

to call events

 Animale animal= new Animal();
 animal.Run += (sender, e) => Console.WriteLine("I'm running. My value is {0}", e.Operation);
 animal.RaiseEvent();

Differences:

  1. You aren't using a public property but a public field (with events the compiler protect your fields from unwanted access)
  2. Events can't directly be assigned. In this case you can't do the previous error that I have showed with overriding the behavior.
  3. No one outside of your class can raise the event.
  4. Events can be included in an interface declaration, whereas a field cannot

notes

EventHandler is declared as the following delegate:

public delegate void EventHandler (object sender, EventArgs e)

it takes a sender (of Object type) and event arguments. The sender is null if it comes from static methods.

You can use also EventHAndler instead this example that use EventHandler<ArgsSpecial>

refer here for documentation about EventHandler

Administrate answered 12/7, 2014 at 11:14 Comment(0)
J
3

Although I've got no technical reasons for it, I use events in UI style code, in other words, in the higher levels of the code, and use delegates for logic that lays deeper in the code. As I say you could use either, but I find this use pattern to be logically sound, if nothing else, it helps document the types of callbacks and their hierarchy too.


Edit: I think the difference in usage patterns I have would be that, I find it perfectly acceptable to ignore events, they are hooks/stubs, if you need to know about the event, listen to them, if you don't care about the event just ignore it. That's why I use them for UI, kindof Javascript/Browser event style. However when I have a delegate, I expect REALLY expect someone to handle the delegate's task, and throw an exception if not handled.

Jauregui answered 19/2, 2009 at 2:2 Comment(1)
Would you elaborate on that as I also make use of evens in UI? A good example would be suffice....thanksPlacentation
G
3

The difference between events and delegates is a lot smaller than I used to think.. I just posted a super short YouTube video on the subject: https://www.youtube.com/watch?v=el-kKK-7SBU

Hope this helps!

Gynaecology answered 25/8, 2017 at 15:2 Comment(1)
Welcome to Stack Overflow! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.Gelation
E
1

If we use only delegate in place of Event then subscriber has the opportunity to clone(), invoke() the delegate itself as shown below in the image. Which is not right.

enter image description here

That's the main difference b/w event and delegate. the subscriber has only one right i.e. listening to the events

ConsoleLog class is subscribing log events via EventLogHandler

public class ConsoleLog
{
    public ConsoleLog(Operation operation)
    {
        operation.EventLogHandler += print;
    }

    public void print(string str)
    {
        Console.WriteLine("write on console : " + str);
    }
}

FileLog class is subscribing log events via EventLogHandler

public class FileLog
{
    public FileLog(Operation operation)
    {
        operation.EventLogHandler += print;
    }

    public void print(string str)
    {
        Console.WriteLine("write in File : " + str);
    }
}

Operation class is publishing log events

public delegate void logDelegate(string str);
public class Operation
{
    public event logDelegate EventLogHandler;
    public Operation()
    {
        new FileLog(this);
        new ConsoleLog(this);
    }

    public void DoWork()
    {
        EventLogHandler.Invoke("somthing is working");
    }
}
Eskridge answered 17/6, 2018 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.