Syntax ElapsedEventHandler in System.Timers.Timer

1

There's a difference between starting a Timer like this:

_timerExam = new Timer();
_timerExam.Elapsed += new ElapsedEventHandler(OnTimedEvent);
_timerExam.Interval = 1000;
_timerExam.Start();

And so?

_timerExam = new Timer();
_timerExam.Elapsed += OnTimedEvent;
_timerExam.Interval = 1000;
_timerExam.Start();

For what is ElapsedEventHandler ?

    
asked by anonymous 12.09.2017 / 19:51

1 answer

3

This is called Method Group Conversion , a feature included with C # 2.

In C # 1, you would have to write the delegate constructor by passing the delegate action ( action ).

_timerExam.Elapsed += new ElapsedEventHandler(OnTimedEvent);

In C # 2 things have changed, you can now let the compiler decide the type delegate compatible with your method signature ( OnTimedEvent ) and target event signature ( Elapsed ). From there the compiler generates the appropriate% with%.

_timerExam.Elapsed += OnTimedEvent;

This is a "trick" or syntactic sugar compiler to decrease the amount of code written by the programmer. In compiled code the delegate operator is used as if you had written it.

    
13.09.2017 / 19:31