views:

510

answers:

4

In C# what is the advantage of

public class blah
{

       public event EventHandler Blahevent;

}

versus

public class blah
{

      private event EventHandler blahevent;

      public event EventHandler Blahevent
      {
          add
              {
                  blahevent+=value;
              } 
              remove
              {
                  blahevent-=value
              }
      }

}

or vice versa.

does the first one open you up to blahinstance.Blahevent = null, or blahinstance.Blahevent(obj,even)

+1  A: 

The second one has the option of controlling exactly what happens when the specified event is subscribed to or unsubscribed from if there is specific logic that needs to run in addition to adding or removing the pointer.

Quintin Robinson
+2  A: 

There is no advantage to explicit implementation of the add/remove methods unless you want to do something different. Possible reasons:

  • Perhaps take control of the event backing code yourself (to directly link to some other event rather than going though a pointless cascade for example)
  • do something else in addition on add or remove
  • Change security demands on the add or remove
  • expose the underlying delegate

What the default implementation does is maintain a private hidden delegate field which is replaced each time a delegate is added or removed. For most cases there is no need to do any of the above but the flexibility is there.

ShuggyCoUk
+1  A: 

You can exclude the delegate from serialization by using the [field: NonSerialized()] attribute on the private field.

JC
I don't understand? do events get serialized?
maxfridbe
Yes, the subscribers would be serialized which is usually not what you want. For instance, if there was a form subscribing to this event you would get an error saying the form is not marked as serializable. So using the attribute gets around that.
JC
+1  A: 

You can place a breakpoint on the latter for debugging purposes. Sometimes this can be really useful (although after debugging I switch it back to the former).

Quibblesome