Delegates and Events: Why we need the event keyword

M

muler

Hi all,

I can't figure out why we need the 'event' keyword, because without
having it I can accomplish the same thing. So, why do we need to put
the event keyword?

namespace DelegateEx
{
delegate void BeastCaptured(string msg);
class A
{
// without having the 'event' keyword added this class can
notify other classes.
// so why do we need the event keyword.

// program behavior same if using: public event BeastCaptured
evt;
public BeastCaptured evt;

public void Loop()
{
for (int i = 0; i < 1000; ++i)
if (i == 666 && evt != null)
{
evt("Beast captured!");
break;
}
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
a.evt += delegate(string msg)
{
Console.WriteLine("Event handled: " + msg);
};

a.Loop();
}
}
}

Output:
Event handled: Beast Captured!

Or, is this working because I put both classes on the same assembly?

Your comments highly appreciated,
Muler
 
J

Jon Skeet [C# MVP]

muler said:
I can't figure out why we need the 'event' keyword, because without
having it I can accomplish the same thing. So, why do we need to put
the event keyword?

See http://pobox.com/~skeet/csharp/events.html for a detailed
explanation.

Events just encapsulate "subscribe" and "unsubscribe" operations. C#
allows "field-like events" which hook these operations up to a delegate
instance, but that's syntactic sugar.

The important thing is that with an event, *all* an outside class can
do is subscribe or unsubscribe: it can't find out existing handlers, or
reset the variable to null etc.
 
M

muler

Seehttp://pobox.com/~skeet/csharp/events.htmlfor a detailed
explanation.

Events just encapsulate "subscribe" and "unsubscribe" operations. C#
allows "field-like events" which hook these operations up to a delegate
instance, but that's syntactic sugar.

The important thing is that with an event, *all* an outside class can
do is subscribe or unsubscribe: it can't find out existing handlers, or
reset the variable to null etc.

Thanks! that is a nice article.

Muler
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top