Search code examples
c#wpfeventsevent-handlingcustom-events

C# - issue with custom raising events


I have my class where I define my event:

public class EventRaiserUtility
{
    public event EventHandler updateList;

    public void updateListEvent()
    {
        if (updateList != null)
        {
            updateList(this, EventArgs.Empty);
        }
    }
    public static EventRaiserUtility raiser = new EventRaiserUtility();
}

and this is where I raise my event:

EventRaiserUtility.raiser.updateListEvent();

and finally this is where I'm trying to create the listener:

...
EventRaiserUtility.raiser.updateList += new EventHandler(raiser_updateList);
//placed in the init method of another class
...

private void raiser_updateList(object sender, EventArgs e)
{
    connType = MainWindowViewModel.getTTC();
}

Simply: this event has to notify when a list is updated and then update another list, with getTTC() with raiser_updateList.

But raiser_updateList is never called. Why? All my 3 snippets of code are in 3 different classes (same project), but this isn't a problem... right?


Solution

  • You're creating a new EventRaiserUtility just before you call updateListEvent (which should have a capital U to follow .NET conventions, by the way; ditto updateList => UpdateList) - but you're creating a separate EventRaiserUtility in order to subscribe to the event. They're different objects, so have different event subscribers. If you always create a new object before raising the event, there could never be any subscribers.

    You should have a single EventRaiserUtility stored in an instance variable in the containing class - you'd create that on construction, then subscribe to the event in one place an raise it in another... but because they'd be talking about the same EventRaiserUtility object, you wouldn't lose the subscription.

    (It's not clear that this utility class actually has much value, to be honest - why aren't you just declaring the event in your class directly? And why declare your own delegate when EventHandler has exactly the same signature?)