Category Archives: Syntax sugar

String templating with dollar sign

There are many different ways to construct a string in C#. One of the most convenient way is to use the dollar sign ($). As shown in this example:

string stringVar = "myStringVar";
int intVar = 2022;
double doubleVar = 2022.22;
object objectVar = new {  objectStringVar = "objectStringVar" , objectIntVar = 22 };

string templatedString = $"This is a stringVar: {stringVar}, " +
    $"that one is an intVar: {intVar}, " +
    $"here comes doubleVar: {doubleVar} , " +
    $"finally the objectVar: {objectVar}";

Console.WriteLine(templatedString);
Console.ReadLine();

This one will produce the following result:

Happy coding!

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!