3

I was wondering what the exact use of events is in c#. I am still in the process of learning c# so I maybe missing something but is it possible to just use delegates.
In this example I wrote a class with a method that counts from 0 to 2^64 and every time it reaches a multiple of a thousand raises an event. Here is the code:

namespace EventDelegate
{
class Program
{
    static void Main(string[] args)
    {
        EventRaiserClass _eventraiser = new EventRaiserClass();
        _eventraiser.handler = SomeEventHandler;
        _eventraiser.handler += AnotherEventHandler;
        _eventraiser.Loop();
        Console.Read();
    }

    static void SomeEventHandler(object sender, EventArgs args)
    {
        Console.WriteLine("Event raised");
    }

    static void AnotherEventHandler(object sendr, EventArgs args)
    {
        Console.WriteLine("Event raised (Another handler)");
    }
}

public delegate void Handler(object sender, EventArgs args);

class EventRaiserClass
{
    public Handler handler;
    public void Loop()
    {
        for (long i = 0; i < Int64.MaxValue; i++)
        {
            if ((i % 1000) == 0)
            {
                EventArgs args = new EventArgs();
                RaiseEvent(args);
                System.Threading.Thread.Sleep(1000);
            }
        }
    }

    private void RaiseEvent(EventArgs args)
    {
        if (handler != null)
            handler(this, args);
    }
}

}

What would the difference have been if I had declared the handler delegate variable to be an event like this public event Handler handler.
Sorry if I am been a bit vague or missing something obvious, but I am just wondering if something else happens behind the scenes when using event rather just using delegates or if it's just for readability purposes.

1 Answers1

2

Events and delegates are similar, but events are more restricted, for good reasons.

In your code, you could do all kinds of things with _eventraiser.handler from the outside. You aren't supposed to do most of those things though.

Consider this line:

_eventraiser.handler = SomeEventHandler;

If you use delegates, you would have to check every time you try to attach an event handler if the delegate is null, and then initialize it with =, and if it is not null, you just have to add handlers with +=. If you forget an initialization, you get a null reference exception, if you put in one too many, you will overwrite all the previous things.

If you use events instead of delegates in this example, you don't have to do any of this, and, in fact, you can't even do it. With delegates you could even take it and then pass it around to some other classes, which could potentially be very dangerous.

The same goes for Invoke, and all the other things you can do with a delegate: They aren't there for events. The only things you can do with an event from an outside class is += and -=, that's it. You can view them as delegates with a special public interface with complicated getters and setters.

(Events also have a special add and remove syntax, but that's a rather uncommonly used feature)

dialer
  • 4,348
  • 6
  • 33
  • 56
  • Thanks for your help. I went back to the code and made the delegate an event after which I got an error on this line `_eventraiser.handler = SomeEventHandler;` which would attempt to overwrite all previously subscribed methods. :-) – c_programmer_jim Apr 01 '13 at 11:40