Hello, World!
In November 2020, Microsoft introduced top-level statements in C# 9 and refined it in C# 10 with global using directives. This sound very complicated for something built for simplicity.
So let's start our journey on programming by the begining...
Console.WriteLine("Hello World!");
This is a complete program. There is no namespace, class or even function defined. With this one line, we introduce only the concepts of literal, function call, argument, and program.
Then we can introduce the concepts of function, parameter, return value, class and namespace by simply writing down what the compiler is generating for us.
using System;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
This mechanism called lowering.
- Lowering
- One semantic technique that consists of, internally, rewriting more complex semantic constructs in terms of simpler ones.
Not all lowering are as impressive as this one but they are really useful when it comes to write expressive code without performance penalty.
For instance, which line is faster ?
var s1 = greeting + ", " + name + "!";
var s2 = $"{greeting}, {name}!";
var s3 = string.Concat(greeting, ", ", name);
In fact, they are same, s1
and s2
are lowered to s3.
Like Stephen Toub said in 2021:
The C# compiler is free to generate whatever code it deems best for an interpolated string, as long as it ends up producing the same result, and today it has multiple mechanisms it might employ, depending on the situation.
But wait, there is more..., in fact, there is lowering all over the place:
var
using
lock
foreach
yield return
/yield break
from ... in ... where ... select ...
async
/await
- ...
So, may be the best lesson to learn here is that we should express our intent in the code, as clearly as possible, and let the compiler tries its best to generate the fastest possible code.