Introduction

C# 9 introduces a super fun feature: Top-level programs. What’s a Top-level program ? This is a simpler way to write your program on its top level: a simpler Program.cs file

Before C# 9 and with C# 9

In your main program you have been able to write whatever you want, for example:

  • async calls (obviously)
  • accessing args (obviously)
  • local functions (obviously again !)
using System;
	using System.Threading.Tasks;

	namespace CSharp9Demo
	{
	    class Program
	    {
	        static async Task Main(string[] args)
	        {
	            // Accessing an argument passed to the program
	            var param = args[0];
	            Console.WriteLine($"You passed the param {param}");

	            // Calling an async service
	            var myservice = new MyService();
	            var result = await myservice.DoWorkAsync();
	            Console.WriteLine(result);

	            // Calling Local function 
	            void DoWork()
	            {
	                Console.WriteLine("This is a local function");
	            }
	            DoWork();

	            Console.ReadLine();
	        }
	    }

	    public class MyService
	    {
	        public async Task<string> DoWorkAsync()
	        {
	            return await Task.FromResult("This is an async method");
	        }
	    }
	}

#.net 5 #csharp #csharp 9 #programming-c

Introducing C# 9: Top-level programs
8.20 GEEK