Skip to main content

Microsoft Silverlight

Answered Question c# custom event kicking up errorsRSS Feed

(0)

lumpenprole
lumpenprole

Member

Member

1 points

8 Posts

c# custom event kicking up errors

So, I'm trying to make a custom event for another object to subscribe to. The frustrating thing is that I've done this a couple times already and it's working, but I'm getting an odd error now. Here's some code:

(inside class declaration)

public delegate void SideSwipeHandler(object ob, EventArgs e);
public event SideSwipeHandler SideSwipe;

(inside a method later on)

EventArgs ev2 = new EventArgs();
SideSwipe(this, ev2);

Here's the error that gets triggered when it reaches the event call:

Object reference not set to an instance of an object.

Any thoughts?

bartczernicki
bartczer...

Contributor

Contributor

4160 points

729 Posts

Answered Question

Re: c# custom event kicking up errors

 You have to make sure the event has subscribers first.  So you can do this a couple ways...

- always define a empty subscriber.  This is a real nice solution if you are doing multithreading and can incurr a very small performance penalty on the event.  Declare your event like this:  public event SideSwipeHandler SideSwipe = delegate { };

This uses an anonymous method to always have one subscriber.

- check the event if it has subscribers always.  If you do the above decleration, you do not need to do this bottom:

 Instead of this: SideSwipe(this, ev2);

Use this:

if (SideSwipe != null)

{

SideSwipe(this, ev2);

}

 

Either way is fine..the second solution is not as nice, because if you DO use multiple threads you can run into a race condition.

 

Please mark as answer if this helped.

 

 

lumpenprole
lumpenprole

Member

Member

1 points

8 Posts

Re: c# custom event kicking up errors

Argh, I can't believe it's that simple. I lost 3 hours to that. Thanks for your help.

JoBone
JoBone

Member

Member

14 points

5 Posts

Re: c# custom event kicking up errors

Thanks, it was simple !!

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities