Custom event accessor error

This works:


public event EventHandler SomeEvent;
...
if (SomeEvent!= null) SomeEvent(this, null);

This doesn’t:


public event EventHandler SomeEvent
{
add { someEventHandlerCount++; }
remove { someEventHandlerCount--; }
}
...
if (SomeEvent!= null) SomeEvent(this, null);

  1. How do I work around this?
  2. If you feel like it, explain why.

I do not understand what you are trying to achieve. The code you say does not work is incorrect syntax,

I think what you try to do is increasing/decreasing a counter every time your event gets subsribed or unsubscribed.
But when defining your add/remove accessor explicitly you have to do the add and remove yourself.

Do it like this (don’t know if it really works like this, but it should, at least similar)


private EventHandler _SomeEvent = new EventHandler(); // don't know if this is really correct, it's been a while I did this
private int someEventHandlerCount = 0;

public event EventHandler SomeEvent
{
   add 
   { 
      someEventHandlerCount++; 
      _SomeEvent += value;
   }
   remove 
   { 
      someEventHandlerCount--; 
      _SomeEvent -= value;
   }
}
...
if (SomeEvent!= null) SomeEvent(this, null);

@ Reinhard Ostermeier - Oh, duh… Thanks

Interesting… I never used the add/remove keywords.

To get the number of registered delegates I would use:

@ Mike - Nice, thanks; now I can get rid of the counter variable!

My starting point was the Gadgeteer driver.
They used the counter in event add/remove like so:


if (counter > 0) EnableInterrupts;
else DisableInterrupts;

When the event is subscribed, interrupts are enabled, and when the last subscriber is removed, they are disabled.


public event EventHandler SomeEvent
{
   add 
   { 
      _SomeEvent += value;
     if (_SomeEvent.GetInvocationList().Length == 1) EnableInterrupts();
   }
   remove 
   { 
      _SomeEvent -= value;
     if (_SomeEvent.GetInvocationList().Length == 0) DisableInterrupts();
   }
}