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.
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With