2

Weirdly I haven't been able to find an answer in the doc or on the web although it seems to be a simple question:

Imagine I registered to a c# event in a conditional block:

void Execute()
{
    if(loader.AlreadyCompleted)
    {
        DoSomething();
    }
    else
    {
        loader.Completed += DoSomething;
    }
}

In this example, a loader will trigger the Completed event. If it already happended AlreadyCompleted will be true, otherwise it is false and I want to register to the Completed event in order to wait before executing DoSomething.

Now imagine that I have an Abort function that could be trigger anytime. In the Abort function I will need to deregister from the Completed event.

void Abort()
{
    loader.Completed -= DoSomething;
}

What will happen if the loader was ready at startup and we never executed the line loader.Completed += DoSomething; ? Can we deregister an event that hasn't been registered? Is there a way to check if we are registered? What's the best practice in this case?

Basile Perrenoud
  • 4,039
  • 3
  • 29
  • 52
  • Have you even tried it? This question look too theoretical to me which makes it too broad. – mrogal.ski Sep 01 '17 at 11:01
  • I hadn't try it when asking. Since I didn't find the answer in StackOverflow I decided to ask, since I'm surely not the only one looking for this info, having the info here can be helpful. I just see that it is a duplicate. That's because I searched using the term "registering" instead of "subscribing", my mistake – Basile Perrenoud Sep 01 '17 at 15:54
  • Please read on what [mcve] is. – mrogal.ski Sep 01 '17 at 15:56

1 Answers1

6

If you try to unregister an event that was never registered nothing will happen. This is due to the idea that when you call loader.Completed -= DoSomething; it’s really just saying loaded.Completed = (Completed)Delegate.Remove(DoSomething). When you try to remove an event handler that was never added or is not there Delegate.Remove will just return null, which sets the loaded.Complete = null.