Earlier I blogged about two new features in C# 9: C# 9 Init-Only Properties and C# 9 Record Type. Another feature in C# 9 that I didn't originally plan on writing about is top-level programs. However, top-level programs do simplify sharing sample code on a blog by removing boilerplate code and nesting. Therefore, I'll probably be using it quite a bit on my blog.
What are Top-Level Programs in C# 9?
As mentioned above, top-level programs in C# 9 reduce the boilerplate code that you see in C# programs. For example, when you create a C# Console Application it comes with the following "hello world" code.
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
With the new top-level programs feature in C# 9, this code can be reduced to the following.
using System;
Console.WriteLine("Hello World!");
That's a heck of a lot easier to read and share on my blog!
Although it's not as obvious, you still have access to any arguments passed to the application.
using System;
string name = args.Length > 0 ? args[0] : "World!";
Console.WriteLine($"Hello {name}!");
And, of course, you can still create methods (which look more like functions now) and access them in top-level programs in C# 9.
using System;
Console.WriteLine(SayHello("World"));
string SayHello(string name)
{
return $"Hello {name}!";
}
When using top-level programs, the top-level statements must come after any using
statements and before any namespace
and type declarations. Therefore, in the example below, the type declaration for Person
must come after the top-level statements.
using System;
var person = new Person("John Doe", 18);
Console.WriteLine(person);
record Person(string Name, int Age) { }
As you can see, the new top-level programs feature in C# 9 is great for sharing code on a blog when you want to reduce the noise of boilerplate code and the amount of nesting. I'll be using this feature quite a bit in the future to share sample code on my blog.