Elapsedeventhandler syntax in System.Timers.Timer

Asked

Viewed 134 times

1

There’s a difference between starting a Timer thus:

_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();

What is the point of ElapsedEventHandler?

1 answer

3


It’s called Method Group Conversion, functionality included with C# 2.

In C# 1, you had to write the constructor of delegate passing as parameter the action (action) that delegate.

_timerExam.Elapsed += new ElapsedEventHandler(OnTimedEvent);

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

_timerExam.Elapsed += OnTimedEvent;

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.