• Differencies: Delegates vs Events

    Published by on March 28th, 2008 10:34 pm under C#

    1 Comment

    While reading C# step by step I found a bit of a dilemma. I couldn’t get the difference between a delegate and an event asides from one needing to be called explicitly (delegate) and the other one doesn’t(event).

    To my understanding the delegate was a way of grouping methods with similar characteristics. i.e.:

    void createdata(); & void destroydata(); void methodname (no parameters);


    int add (int a, int b); & int substract(int a, int b); int methodname (int, int);

    Once grouped into a single delegate they could be called at once. This was really similar to what the event did. It could group either methods or delegates (who at the same time group methods, otherwise they would be pointless to have).

    The only difference I could find was that while the delegate is declared i.e.:

    delegate void Accelerate();

    the event containing the TakeOff() delegate would be declared some sort of:

    event Accelerate PushLever;

    being event only a modifier.

    Some research (http://blog.monstuff.com/archives/000040.html is the web page where I got the information to help me understand some of this) showed me the some differences between the two of them:

    • Events can be included in an interface, delegates cannot.
    • Events’ scope for invocation only includes the class that declares it, delegates depend on their modifier (public | private| protected)
    • Events come with their own custom “get and set” accessors for getting or removing other methods (add, remove)
    • The signature of any delegate that is used as an event should be: “The signature should be foo(object source, EventArgs e), where source is the object that fired the event and e contains any additional information about the event.”(http://blog.monstuff.com/archives/000040.html)

    From my point of view without thinking about programming semantics, an event, as the word states is easier to imagine representing something that happens in real life as a result of an action. This thing that happens triggers a set of actions (the delegate). Each small action of this set would be the methods assigned to this delegate.

    Back to the plane example, the event is pushing the lever. The objective of doing this is getting the plane to take off. In order to do this, the plane must accelerate thus making the engines work harder (method) and set the wings straight(method). (Maybe the plane wasn’t the best example since I clearly don’t know how it works, but I hope you can get the point).

Archives

Categories