Tag Archives: console app

One liner event subscription in C#

Generally an event subscription looks something like this:

// Creating a timer
System.Timers.Timer t = new(1000);
// Subscribing on it's elapsed event
t.Elapsed += T_Elapsed;
// Starting the timer
t.Start();
// Implementing the timers' elapsed event
void T_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("Tick!");
}
// Not letting the app to exit
Console.ReadLine();

We have an event emitter, the timer, and we are subscribing and implementing a method when that event is emitted.

It is possible to shorten this event implementation in one line:

// Creating a timer
System.Timers.Timer t = new(1000);
// Subscribing and implementing on it's elasped event
t.Elapsed += (_, _) => { Console.WriteLine("Tick!"); };
// Starting the timer
t.Start();
// Not letting the app to exit
Console.ReadLine();

Note: the (_, _) is equal to (sender, e), we just shorten them because we won’t use them.

Although it can be convenient to use this form regularly, but take care and keep the code readable!

Happy coding!