Groups | Blog | Home
all groups > c# > august 2004 >

c# : raising events in C#


walker_712 NO[at]SPAM hotmail.com
8/29/2004 11:42:26 PM
When I raise an event I have to first test to see if the event has
been created. For example:

class ClassX
{
public event System.EventsArgs MyEvent;

public void SomeMethod()
{
if (MyEvent != null) MyEvent();
}
}

If there a way of creating the event variable (MyEvent) so it's list
is empty and when I write:

public void SomeMethod()
{
MyEvent();
}

it won't cause an exception and it will raise the event for each
subscriber in the list (and if nobody has subscribed the list will be
empty)?

Thanks in advance,
Rakesh Rajan
8/29/2004 11:59:02 PM
I don't know of any straight forward means for that....but of course you
could abstract it by using a simple method, and then invoke the method
instead....this would bring down the if block to a single line of code.


[quoted text, click to view]
Nicholas Paldino [.NET/C# MVP]
8/30/2004 9:49:16 AM
Darren,

There is no way to do this, unless, as previously suggested, you create
a dummy event handler. This, IMO, is wasteful.

One important thing to point out. The way that you are firing events is
wrong, as it is not thread-safe. The recommended way for firing an event is
to assign the delegate list to a local parameter, and then check that for
null. If it is not, then fire that. The thing is between the check for
null and the firing of the event, the invocation list could have changed,
and could introduce an error.

So, you want to do this:

// Assign to local variable.
EventHandler eventHandler = MyEvent;

// Check for null.
if (eventHandler != null)
// Fire.
eventHandler(this, EventArgs.Empty);

Also, your declaration of your event is wrong, it should be:

public event System.EventHandler MyEvent;

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com

[quoted text, click to view]

Niki Estner
8/30/2004 12:58:54 PM
Add an empty dummy event handler in the constructor.

Niki

"Darren" <walker_712@hotmail.com> wrote in
news:cd9d3666.0408292242.5d1e9996@posting.google.com...
[quoted text, click to view]

walker_712 NO[at]SPAM hotmail.com
8/30/2004 7:01:18 PM
Thanks Nicholas. Your answer wasn't what I was expecting but just the
AddThis Social Bookmark Button