2

I'm following this tutorial to write a Windows Service. Every 60 seconds, a new event is raised that writes to the event log. In the code, the new event is raised using the += operator.

// Set up a timer that triggers every minute.
Timer timer = new Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();

Whats the motivation for using this operator here? Why is it not just =? Especially the + part seems to confuse me..

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
TMOTTM
  • 3,286
  • 6
  • 32
  • 63
  • Possible duplicate of [Understanding events and event handlers in C#](https://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c-sharp) – Owen Pauling Aug 22 '19 at 09:29

1 Answers1

1

Elapsed is an event. From ECMA-334 C# Language Specification, chapter 15.8.1:

The only operations that are permitted on an event by code that is outside the type in which that event is declared, are += and -= .

Just assignment = would be a syntax error here. And this makes sense, because delegates in C# may have many subscribers. From ch.20.1

delegate instance encapsulates an invocation list, which is a list of one or more methods

So there are might be several handlers of Elapsed event, and += is just an appending another one.

Renat
  • 7,718
  • 2
  • 20
  • 34