using the event keyword

M

Mark Broadbent

hi guys, i am currently studying through my book and wonder if somebody
could clear this up before i have to look at other sources.

I have code which defines and creates an event object using a delegate
as the handler as thus..
//Start of code
using System;

// Declare a delegate for an event.
delegate void MyEventHandler();

// Declare an event class.
class MyEvent {
public event MyEventHandler SomeEvent;

// This is called to fire the event.
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();
}
}

class EventDemo {
// An event handler.
static void handler() {
Console.WriteLine("Event occurred");
}

public static void Main() {
MyEvent evt = new MyEvent();

// Add handler() to the event list.
evt.SomeEvent += new MyEventHandler(handler);

// Fire the event.
evt.OnSomeEvent();
}
}
//end of code

Now I dont really have a problem with the code, it all makes sense, but
my question is what added benefit does using the event keyword when
declaring the SomeEvent delegate. By removing this it still runs fine
so does creating this event object(as opposed to a basic delegate
object) provide me with additional functionality or flexibility?

Thanks in advance,
Br,
Mark.
--

Br,
Mark Broadbent
mcdba , mcse+i
=============
 
M

Mark Broadbent

Hi Jon.
You had to make me read thru that didnt you! LOL.
From the article I gathered that the use of event keyword adds a degree of
protection on the delegate list outside of the class and that it can only be
modified thru the -= and += operators.
Hope this was correct.

Cheers for the help.
Br,

Mark.
 
J

Jon Skeet [C# MVP]

Mark Broadbent said:
You had to make me read thru that didnt you! LOL.

I'd rather give more information than less - particularly when it's so
easy to do, just by giving a link :)
From the article I gathered that the use of event keyword adds a degree of
protection on the delegate list outside of the class and that it can only be
modified thru the -= and += operators.
Hope this was correct.

Yup, that's right.
 

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