maxfridbe
maxfridbe

Reputation: 5970

C# Event Subscription

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)

Upvotes: 1

Views: 2234

Answers (4)

Quibblesome
Quibblesome

Reputation: 25429

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).

Upvotes: 1

ShuggyCoUk
ShuggyCoUk

Reputation: 36476

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.

Upvotes: 2

JC.
JC.

Reputation: 11801

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

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82375

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.

Upvotes: 1

Related Questions