Skip to main content
Home Forums Silverlight Programming Programming with .NET - General c# custom event kicking up errors
3 replies. Latest Post by JoBone on January 16, 2009.
(0)
lumpenprole
Member
1 points
8 Posts
11-06-2008 7:44 PM |
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?
bartczer...
Contributor
4160 points
729 Posts
11-06-2008 10:09 PM |
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.
11-07-2008 12:12 PM |
Argh, I can't believe it's that simple. I lost 3 hours to that. Thanks for your help.
JoBone
14 points
5 Posts
01-16-2009 1:36 PM |
Thanks, it was simple !!