Jack Kada
Jack Kada

Reputation: 25232

Wrong Code In C# Via CLR Book

I am reading this book and am stuck here:

public static class EventArgExtensions { 
   public static void Raise<TEventArgs>(this TEventArgs e,  
      Object sender, ref EventHandler<TEventArgs> eventDelegate)  
      where TEventArgs : EventArgs { 

      // Copy a reference to the delegate field now into a temporary field for thread safety  
      EventHandler<TEventArgs> temp =  
         Interlocked.CompareExchange(ref eventDelegate, null, null); 

      // If any methods registered interest with our event, notify them   
      if (temp ! = null) temp(sender, e); 
   } 
}

Specifically the MSDN doc says that

public static object CompareExchange(ref object location1, object value, object comparand)

Member of System.Threading.Interlocked

Summary:
Compares two objects for reference equality and, if they are equal, replaces one of the objects.

Parameters:
location1: The destination object that is compared with comparand and possibly replaced.
value: The object that replaces the destination object if the comparison results in equality.
comparand: The object that is compared to the object at location1.

Returns:
The original value in location1.

Exceptions:
System.ArgumentNullException: The address of location1 is a null pointer.

which means that this is wrong :

 EventHandler<TEventArgs> temp =  
             Interlocked.CompareExchange(ref eventDelegate, null, null); 

          // If any methods registered interest with our event, notify them   
          if (temp ! = null) temp(sender, e); 

because I need to be checking what was passed in to CompareExchange and not the output.

Am I missing something?

Upvotes: 1

Views: 218

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501113

No, the code is fine. It's effectively just a way of performing a volatile read. It will only return null if it replaced null with null - i.e. if eventDelegate is null.

Upvotes: 8

Related Questions