.NET 5 mini me or Top-level statements

Hello mini me

So when you create a new .net 5 console app you just create a new from the command-line

c:\source\> mkdir mini5
c:\source\> cd mini5
c:\source\mini5> dotnet new console
c:\source\mini5> code .

And you get this

using System;

namespace mini5
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Which of course gives us this:

c:\source\mini5> dotnet run
Hello World!
c:\source\mini5>

But his can be minified to this

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World!");
    }
}

or this, throuh the magic of C# 9

static void Hello()
{
    System.Console.WriteLine("Hello World!");
}

Hello();

or even this:

System.Console.WriteLine("Hello World!");

And there we have it. The new Top-level statements in .NET 5

WHY OH WHY DEAR GOD! WHY! SAVE FROM THIS ABOMINATION!!!

We have come so far in building well structured applications, why do we want this?

Of course so we ca do this:

Hello:
    System.Console.WriteLine("Hello World!");
    goto Hello;

The world needs more hello:

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

This could easily be my longest post to date :)

But seriously, I do see some usages. It does provide a nice clean simple intro pathway into the “super complex” static Main method.

So what happens if you have multiple files? The compiler provides a CS8802 error which states you can’t, which makes sense. How would that get assembled? in which order?

Considering the statements gets wrapped in a main method behind the scenes, what happens with a using statement? It works fine! Magic I tell you! Magic!

using System;

Console.WriteLine("Hello World!");

But what about the arguments you declare in Main you ask? Simple, the args are implicitly declared.

using System;

Console.WriteLine("Hello " + String.Join(" ", args));

But that begs another question. How do you actually pass arguments when you use “dotnet run”. Lets try to ask dotnet.

c:\source\mini5> dotnet run --help
Usage: dotnet run [options] [[--] <additional arguments>...]]
...bla bla bla...

So this would simply be:

c:\source\mini5> dotnet run -- Are we at Christmas yet?
Hello Are we at Christmas yet?

Maybe this would be the day I introduce my kids to .net :)