raising events in C#

D

Darren

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,
Darren.
 
G

Guest

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
D

Darren

Thanks Nicholas. Your answer wasn't what I was expecting but just the
answer I was looking for.
 

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