C## 9.0 introduces many new language features, and with this blog post I start a little series to look at some of those new features. Let’s start in this post with top-level statements.

When you create a new Console application with C#, you get a lot of boilerplate code. Below you see the code of a new app with the name ThomasClaudiusHuber.ConsoleApp.

using System;

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

If you’re new to C#, this program will confront you with a lot of concepts:

  • using directives
  • namespaces
  • blocks { }
  • classes
  • static methods
  • array parameters
  • Console.WriteLine statement

Already in earlier versions of C## and .NET the namespace was optional. Also the args parameter of the Main method is optional. You could write the program like this without the namespace block and the args parameter:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello World!");
    }
}

This means, from our list, you can remove namespaces and array parameters:

  • using directives
  • namespaces
  • blocks { }
  • classes
  • static methods
  • array parameters
  • Console.WriteLine statement

C## 9.0, which comes out with .NET 5, brings all of this to the next level by allowing so-called top-level programs. That means you can write statements directly at the top-level of a file. There’s no need to define a class and a static Main method. The code below shows a Hello World Console app written with C## 9.0:

using System;

Console.WriteLine("Hello World!");

Now, when you look at the list of features that we have here compared to the original Console app, it looks like below. Only the using directive and the Console.WriteLine statement are left:

  • using directives
  • namespaces
  • blocks { }
  • classes
  • static methods
  • array parameters
  • Console.WriteLine statement

This makes it clear that simple top-level programs are an easy way to start with C#. Beginners don’t have to learn all the different features from the beginning.

#.net #c# #csharp #programming-c

C# 9.0: Top-level Statements
3.35 GEEK