JerberSoft

hello there again people. i have been confused in c# events programming.


i have this code and i have a form with 1 button named button1.

Re: Windows Forms General Events question

Mark Dawson

Hi,

the issue you are having is that the event keyword is really a bit of syntactic sugar. When you class is compiled each event is really replaced by a class field of the type of delegate associated with the event and two new methods are added that allow you to add delegates and remove delegates from the underlying multicast delegate, initially this delegate field is null.

So when you raise an event it is really invoking all of the delegates in the underlying multicast delegates invocation list, if you have not assigned any listeners then the delegate is still null and you will get an error.

In C# it is standard practise when writing events to create a protected virtual method that will raise an event ie.

protected virtual void OnFinished(string text, int x)

{

if(Finished != null)

{

Finished(text, x);

}

}

Then whenever you want to raise the event you call the OnXXXX method instead, this is also necessary if you want to raise an event from a derived class that is defined in the base class, because you can only raise events from the class in which they were defined, however you can call your protected virtual OnXXXX method from the derived class or even override it.

As a note, the above code is not thread safe, since after you check "Finished != null" it is possible another thread can remove the last event handler and cause you to get a null reference exception, so if you are using multi-threading in your application you need to be a bit more careful.

Mark.






Re: Windows Forms General Events question

Keith Rome

Events are really objects. More than that, they are collections of objects (represented by the internal .NET MulticastDelegate class). Just because you have declared a static event field variable does not mean that it will have a value. In fact, until you hook your first handler up to the event, it will not have a value at all - they default to null.

All you have to do is check for Finished != null before attempting to invoke it...

if (Finished != null)
{
Finished("You have reached the finish line.", x);
}

HTH






Re: Windows Forms General Events question

JerberSoft

thanks to both of you. so thats how to approach events programming as well. ;-)