C# Timer With Lambda Instead of Method Reference?

Let's say I have the following code:

var secondsElapsed = 0;

Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler( iterateSecondsElapsed);
myTimer.Interval = 1000;
myTimer.Start();


//Somewhere else in the code:
public static void iterateSecondsElapsed( object source, ElapsedEventArgs e )
{
    secondsElapsed++; 
}

Is there any way to do this WITHOUT defining the DisplayTimEvent static method? Something like:

myTimer.Elapsed += new ElapsedEventHandler( secondsElapsed => secondsElapsed ++);

I realize I am showing a profound lack of understanding of lambdas here, but nonetheless...

Jon Skeet
people
quotationmark

Sure, just:

myTimer.Elapsed += (sender, args) => secondsElapsed++;

The parameters for the lambda expression have to match the parameters for the delegate that you're trying to convert it to, basically.

Depending on whether the Timer you're using always fires on the same thread or not, you may want to use:

myTimer.Elapsed += (sender, args) => Interlocked.Increment(ref secondsElapsed);

people

See more on this question at Stackoverflow