This is the first in a series of articles on new features introduced in C#9.

Top-level statements allow you to simplify and remove some of the “ceremony” in your code.

For example, take the following console application written in C#8:

?

using System.Linq;

using static System.Console;

namespace ConsoleAppCS8

{

class Program

{

static int Main(string[] args)

{

string greeting = ""``;

if (args.Any())

{

greeting = args[0];

}

WriteLine(``"Please enter your name"``);

var name = ReadLine();

var upperName = ConvertToUpper(name);

WriteLine($``"{greeting} {upperName}"``);

return 42;

}

public static object ConvertToUpper(string name)

{

return name.ToUpperInvariant();

}

}

}

In the preceding code the “ceremony” consists of things such as the enclosing namespace, the Program class outline, and the Main method itself.

With top-level statements in C## 9 this code can be simplified to the following:

?

using System.Linq;

using static System.Console;

string greeting = ""``;

if (args.Any())

{

greeting = args[0];

}

WriteLine(``"Please enter your name"``);

var name = ReadLine();

var upperName = ConvertToUpper(name);

WriteLine($``"{greeting} {upperName}"``);

return 42;

static object ConvertToUpper(string name)

{

return name.ToUpperInvariant();

}

Notice in the C## 9 version that the structure is a lot “flatter” because there are no nested {} from the namespace, class, and Main method.

The application will still act in the same way, there is just less boilerplate code.

#icymi c# 9 #c# 9 #new features

 ICYMI C# 9 New Features: Top-level Statements
1.25 GEEK