Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# add event handler literal code block

Is it possible to add a literal code block as an event handler in C#? Something like:

Timer t = new Timer(1000);
t.Elapsed += new ElapsedEventHandler({ Console.WriteLine("Tick"); });

You can do this in PowerShell, so I thought there might be some way to do this in C# too.

like image 502
Joshua Honig Avatar asked Aug 25 '26 08:08

Joshua Honig


1 Answers

You can use a lambda expression (C# 3.0 and higher):

t.Elapsed += (sender, args) => Console.WriteLine("Tick");

or an anonymous method (C# 2.0 and higher):

// If you don't need the parameter values
t.Elapsed += delegate { Console.WriteLine("Tick"); };

// If you do need the parameter values
t.Elapsed += delegate(Object sender, ElapsedEventArgs args) {
    Console.WriteLine("Tick from {0}", sender); 
};
like image 50
Jon Skeet Avatar answered Aug 27 '26 23:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!