rahul dhawan
rahul dhawan

Reputation: 37

Additional functionality Events provide over delegate

As I understand an Event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

But as demonstrated in following code above said functionality can also be achieved by delegate only i.e. without using delegate.

class Program
{
    static void Main(string[] args)
    {
        ListWithChangedEvent lwce = new ListWithChangedEvent();
        lwce.delegateVariable = DelegateTestMethod;
        lwce.Add("test");

        Console.ReadLine();
    }

    public static void DelegateTestMethod(object sender, object e)
    {

    }
}

public delegate void ChangedEventHandler(object sender, object e);

public class ListWithChangedEvent : System.Collections.ArrayList
{
    public override int Add(object value)
    {
        int result = base.Add(value);
        if (delegateVariable != null)
            delegateVariable(this, "");
        return result;
    }

    public ChangedEventHandler delegateVariable;

}

So, I was wondering what additional functionality does Events provide?

Upvotes: 1

Views: 662

Answers (3)

Royi Namir
Royi Namir

Reputation: 148524

event is just the access approach to the handler.

it wont allow you to do myHandler=myFunc; only using += ( from outer class)

it was made that if another dumb use your code - so he wont destroy your chain by using = so you allow him only += or -=

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564403

So, I was wondering what additional functionality does Events provide?

Events provide two distinctly different advantages over exposing a public delegate:

  1. You're making the intent very clear. A delegate is typically exposed publically for a very different purpose than an "event" - by using an event, you're very clearly saying "this is something that will get raised at a specific point". Exposing a delegate typically has a different meaning - most often a delegate in a public API is a required input for that API - ie: something that is used directly by the method, not an optional notification mechanism triggered by the method.
  2. Events, technically, are not necessarily just a delegate. An event actually has the option of allowing custom add and remove accessors, which allow you to manually determine what happens when a subscriber subscribes or unsubscribes from the event. For example, many implementations of ICommand.CanExecuteChanged actually don't include their own delegate at all - but silently route to the CommandManager's RequerySuggested event.

Upvotes: 5

Moo-Juice
Moo-Juice

Reputation: 38825

Your example allows for a single delegate to be called. The event is a collection of delegates, meaning you can += and -= your heart away (even during event invocation).

Upvotes: 0

Related Questions