0

I'm modeling my C# 4.0 event handler logic after this SO answer and get the error

ThresholdExceededEvent can only appear on the left hand side of += or -=

Code

    private EventHandler<EventLogAlert> thresholdExceededEventDelegate;
    public event EventHandler<EventLogAlert> ThresholdExceededEvent
    {
        add { thresholdExceededEventDelegate += value; Console.WriteLine("add operation"); }
        remove { thresholdExceededEventDelegate -= value; Console.WriteLine("remove operation"); }
    }

    protected virtual void OnThresholdExceededEvent(EventLogAlert e)
    {
        EventHandler<EventLogAlert> handler = ThresholdExceededEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }

but it compiles when I do this....

   public event EventHandler<EventLogAlert> ThresholdExceededEvent;
    protected virtual void OnThresholdExceededEvent(EventLogAlert e)
    {
        EventHandler<EventLogAlert> handler = ThresholdExceededEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }

What is the preferred approach?

Community
  • 1
  • 1
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
  • You can access the delegate directly instead of the event e.g. "handler = thresholdExceededEventDelegate;" – Peter Ritchie May 15 '12 at 03:39
  • it can be done, but i suppose it is done to make it more [thread safe](http://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety) – Tilak May 15 '12 at 03:46

2 Answers2

4

Instead of

EventHandler<EventLogAlert> handler = ThresholdExceededEvent;

Use

EventHandler<EventLogAlert> handler = thresholdExceededEventDelegate;
Tilak
  • 30,108
  • 19
  • 83
  • 131
0

Use the second approach; if you don't need custom handling of attaching to and detaching from the event (and you aren't trying to implement an interface's event explicitly), then there's no need for the more verbose syntax of the first option; the code in the second will compile down to something very closely resembling the second option, anyway.

The syntax error in your first block of code is that you're trying to execute an explicitly-implemented event directly. You'll need to execute the delegate itself rather than the event in that case.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343