Top Level Programs In C# 9

Getting Setup With C# 9

If you aren’t sure you are using C# 9 and/or you want to start using some of the new shiny features in the C# language, be sure to read our quick guide on getting setup with C# 9 and .NET 5. Any feature written about here is available in the latest C# 9 preview and is not a “theoretical” feature, it’s ready to go!

C# 9 Features

We are slowly working our way through all new C# 9 features, if you are interested in other new additions to the language, check out some of the posts below.

Free C# 9 Video Course

Are you one of those people that sees a big wall of text on a programming blog and instantly tunes out? Well you aren’t alone! In fact, I got hassled so much with people asking me “Can’t you just quickly share your screen and show me?” rather than reading a blog post, I decided I may as well quickly record the need to know bits of C# 9. So that’s what I’ve done!

My “What’s New In C# 9” course is completely free and will get you up and using C# 9 features in less than an hour (seriously!). Did I mention it’s FREE?

Watch For Free Now!

A Console Application Today

Start any new console application today from Visual Studio, and you’ll see something like this :

using System;

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

A bog standard console application that says Hello World. Not a heck of a lot going on here. But in many ways, it’s ever so slightly over engineered. Show this to a new programmer as their “first” program. And they’ll say “But what’s this namespace thing?” “What does static mean?” “What are args? Do I use them or?”. There’s just ever so much going on for such a simple program.

And taking it further, this isn’t limited to newbie programmers. It can be frustrating when you just want to “script” something, and you have all this boiler plate. And that’s what Top Level Programs solves.

Top Level Programs

Top level programs (also referred to as Top Level Statements) does away with this. We can take our simple application and turn it into :

using System;

Console.WriteLine("Hello World!");

That’s it! No more namespace, no more program class, just a bog standard simple script. In some ways, if you are a fan of using things like Linqpad, this is a very similar experience.

And I mean.. That’s it.. That’s top level programs! There really isn’t much more to it!

If you want to get started, as of today, there isn’t a Visual Studio template for writing everything top level (Well.. I mean that would just be a blank file). But if you create a new console application, then ensure you are using C# 9 by editing your .csproj to match the below :

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
    <LangVersion>9.0</LangVersion>
  </PropertyGroup>
</Project>

Then you should be able to essentially delete everything in your program.cs and start fresh.

Using Async

Want to use an sync method, no problem. Check this out :

using System;
using System.Threading.Tasks;

await MyAsyncMethod();
Console.WriteLine("Hello World!");

async Task MyAsyncMethod()
{
    await Task.Yield();
}

Using await tells the compiler that the compiled main entry point should also be async. And we are also showing off the fact that you can add in local method to this top level file to. It may just be the return of the one file wonder!

Using Args

Missing Args? No problem.

using System;
Console.WriteLine(args[0]);

Your args are still there, just not as obvious!

Who Is This For?

So finally, a quick note on who this is for. I don’t really feel like this is aimed at any one level of C# developer. While it’s helpful for newbies to find their footing in a more “scripting” environment, the fact that you can now just whip up a quick one file wonder without all the cruft of your regular console app is actually amazingly useful at any level.

I actually have a sneaking suspicion that those developers who fell in love with NodeJS with it’s simple one file APIs may also like the simplicity of this one. Imagine just being able to create a dead simple API that can return some lookup value, and it’s just a matter of opening up an empty file and typing.

Troubleshooting

If you get the following error :

The feature 'top-level statements' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.

It means you are using a version of C# less than 9 (Or atleast not with the latest preview version). Check out our quick guide on getting setup with using C# 9 and all it’s features here : https://dotnetcoretutorials.com/2020/08/07/getting-setup-with-c-9-preview/

ENJOY THIS POST?
Join over 3.000 subscribers who are receiving our weekly post digest, a roundup of this weeks blog posts.
We hate spam. Your email address will not be sold or shared with anyone else.

Leave a Reply

Your email address will not be published. Required fields are marked *