Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 79293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T21:07:23+00:00 2026-05-10T21:07:23+00:00

In a code review, I stumbled over this (simplified) code fragment to unregister an

  • 0

In a code review, I stumbled over this (simplified) code fragment to unregister an event handler:

 Fire -= new MyDelegate(OnFire); 

I thought that this does not unregister the event handler because it creates a new delegate which had never been registered before. But searching MSDN I found several code samples which use this idiom.

So I started an experiment:

internal class Program {     public delegate void MyDelegate(string msg);     public static event MyDelegate Fire;      private static void Main(string[] args)     {         Fire += new MyDelegate(OnFire);         Fire += new MyDelegate(OnFire);         Fire('Hello 1');         Fire -= new MyDelegate(OnFire);         Fire('Hello 2');         Fire -= new MyDelegate(OnFire);         Fire('Hello 3');     }      private static void OnFire(string msg)     {         Console.WriteLine('OnFire: {0}', msg);     }  } 

To my surprise, the following happened:

  1. Fire('Hello 1'); produced two messages, as expected.
  2. Fire('Hello 2'); produced one message!
    This convinced me that unregistering new delegates works!
  3. Fire('Hello 3'); threw a NullReferenceException.
    Debugging the code showed that Fire is null after unregistering the event.

I know that for event handlers and delegate, the compiler generates a lot of code behind the scene. But I still don’t understand why my reasoning is wrong.

What am I missing?

Additional question: from the fact that Fire is null when there are no events registered, I conclude that everywhere an event is fired, a check against null is required.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T21:07:24+00:00Added an answer on May 10, 2026 at 9:07 pm

    The C# compiler’s default implementation of adding an event handler calls Delegate.Combine, while removing an event handler calls Delegate.Remove:

    Fire = (MyDelegate) Delegate.Remove(Fire, new MyDelegate(Program.OnFire)); 

    The Framework’s implementation of Delegate.Remove doesn’t look at the MyDelegate object itself, but at the method the delegate refers to (Program.OnFire). Thus, it’s perfectly safe to create a new MyDelegate object when unsubscribing an existing event handler. Because of this, the C# compiler allows you to use a shorthand syntax (that generates exactly the same code behind the scenes) when adding/removing event handlers: you can omit the new MyDelegate part:

    Fire += OnFire; Fire -= OnFire; 

    When the last delegate is removed from the event handler, Delegate.Remove returns null. As you have found out, it’s essential to check the event against null before raising it:

    MyDelegate handler = Fire; if (handler != null)     handler("Hello 3"); 

    It’s assigned to a temporary local variable to defend against a possible race condition with unsubscribing event handlers on other threads. (See my blog post for details on the thread safety of assigning the event handler to a local variable.) Another way to defend against this problem is to create an empty delegate that is always subscribed; while this uses a little more memory, the event handler can never be null (and the code can be simpler):

    public static event MyDelegate Fire = delegate { }; 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 81k
  • Answers 81k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I just wrote a quick plugin to run a test… May 11, 2026 at 4:33 pm
  • Editorial Team
    Editorial Team added an answer It's a pointer to a pointer, just like in C… May 11, 2026 at 4:33 pm
  • Editorial Team
    Editorial Team added an answer The response object should have a setContentLength method: // Assumes… May 11, 2026 at 4:33 pm

Related Questions

A coworker claimed recently in a code review that the [[ ]] construct is
I am performing a code review (VS2008/.NET 3.5). The development team has created several
I'm working on the K&R book. I've read farther ahead than I've done exercises,
Question My question is how can you teach the methods and importance of tidying-up

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.