using the event keyword vs. not doing so  
Author Message
Code Digger





PostPosted: Visual C# General, using the event keyword vs. not doing so Top

I'm trying to understand the differnce between declaring a variable/object with/without event keyword. Till now I could not determin any difference. Does anybody know any difference besides the word "event"

The following displays exactly the same behaviour for notifyHandler and ne:

delegate void NotifyEvent(string s);

event NotifyEvent notifyHandler;

NotifyEvent ne;

private void doNotify(string text) {

MessageBox.Show("kjashlkajsd", text);

}

private void button1_Click(object sender, EventArgs e) {

if (notifyHandler != null) {

Delegate[] dl = notifyHandler.GetInvocationList();

foreach (NotifyEvent d in dl)

notifyHandler -= d;

}

notifyHandler += new NotifyEvent(doNotify);

notifyHandler.Invoke("huhu");

notifyHandler += new NotifyEvent(doNotify);

ne = notifyHandler;

ne += new NotifyEvent(doNotify);

ne.Invoke("wow");

}



Visual C#19  
 
 
Dah_cn





PostPosted: Visual C# General, using the event keyword vs. not doing so Top

See sample below:

class Program
{
class MyClass
{
public event EventHandler MyEvent;
public EventHandler MyHandler;

public void FireEvent()
{
if (MyEvent != null)
{
MyEvent(null, null);
}
if (MyHandler != null)
{
MyHandler(null, null);
}
}
}

static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.MyEvent += new EventHandler(mc_MyEvent);
mc.MyHandler += new EventHandler(mc_MyHandler);
mc.MyHandler = null; // This is OK
mc.MyEvent = null;
// But for an event, you can't do this.
mc.FireEvent();
}


static void mc_MyHandler(object sender, EventArgs e)
{
Console.WriteLine("mc_MyHandler Invoked");
}

static void mc_MyEvent(object sender, EventArgs e)
{
Console.WriteLine("mc_MyEvent Invoked");
}
}

So if you set an event to null, you will get an error:

Error 1 The event 'ConsoleApplication1.Program.MyClass.MyEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ConsoleApplication1.Program.MyClass')

This may help you to understand: http://blog.monstuff.com/archives/000040.html



 
 
Code Digger





PostPosted: Visual C# General, using the event keyword vs. not doing so Top

Thanks, the supplied link was especially helpful.