C# 9 comes with many new features to enhance productivity and fix bugs. One productivity enhancement comes for small programs and learning C#: top level statements. This also allows for a new way to create a Hello World program with C#. It’s not the first time that a new C# language feature made a change for Hello World. This also happened with C# 6. Let’s come on a tour how Hello World changed during the C# years, and what’s going on with top level statements and functions.

Hello World

C# 1

The first version of C# was influenced by Java, Delphi, and C++. To create a simple Hello World application, the Main method had to be defined as the entry point into the application. With this object-oriented programming language every method had to be put into a type, e.g. the Main method into the Program class. To write a string to the console, the WriteLine method of the Console class can be used. The Console class is defined within the System namespace, so the using declation openend this namespace:

using System;

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

C# 6 – Using Static Directive

Following the different versions of C#, every new version offers many new features – just a few mentioned here are generics, LINQ, and async/await. The Hello World application didn’t change – up to C# 6. With C# 6 using static was added which allows to open all members of a static type. It’s no longer needed to use the class name when invoking a static method. The first time with C# the Hello World application was changed. The WriteLine method can be invoked without the class name:

using static System.Console;

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

C# 9 – Top-Level Statements

It took some years for the next simplification of Hello World. With C# 9 Top-level statements, it’s no longer necessary to delcare the Main method at all. Just add method invocations top-level.

using System;

Console.WriteLine("Hello World!");

Behind the scenes, the compiler creates a $Program class and a $Main method:

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

#csharp #csharp9 #function

How Hello World! changed – top level statements and functions (C# 9)
1.65 GEEK