Top Level Programs in C# 9

12/12/2020 c# dotnet

Top Level Programs are a newly available feature in C#. In this post we will have a look at how it is different in C# 9 and what we can do in top level programs.

Firstly, lets have a look at a default Program.cs file. I have run a "dotnet new" command for console application in Power Shell:

dotnet new console command

The code snippet below shows what we will be used to as C# developers for our Program.cs file, including a namespace, Program class and Main method.

Snippet 1 👩‍💻:

When we build and run, as we'd expect it says "Hello World!"

dotnet build and not new run resulting in "hello world!"

In C# 9, we can minimise this to only contain the code in snippet 2, you will notice this is alot less code and these namespace, class name and method definition we are used to seeing are no longer there. For us experienced C# developers this may be very strange (and a little unsettling?) but I think this will be great for developers new to C#. Snippet 3 shows an even shorter version where we don't even have the using file!

Snippet 2 👩‍💻:

Snippet 3 👩‍💻:

Next up, let's have a look at how we can create a method in a top level program. I discussed new C# 9 features at a local meetup, so you will notice the examples are in that context. 

We can add our method to the top level program, "GetMessage()" in this example, and call it from our program to generate our console output message.

Snippet 4 👩‍💻:

We can also add classes in to our top level program. So we can define a class to then use in our console app program class. See in snippet 5, I have created a "Meetup" class, a type where we can define a meetup object with a City and Topic fields. I have now refactored the code to initialise an object of type Meetup and pass it in to our "GetMessage" method.

Note: order matters here, type definitions need to be after your top level program logic.

Snippet 5 👩‍💻:

Here's the output of the application running:

Thoughts?

When discussing this at meetups with other developers, there were alot of opinions on top level programs and if they are something we'd use and if they follow conventions we are used to in our lives as a C# object orientated developer. However, I think it will be great for 2 scenarios: building quick scripts in C# and for new developers or folks new to .Net and C# to get started. Anything that makes code more accessible to get started with is a positive to me 😊

What do you think? Let me know on twitter.

Related Posts