In this short tutorial, you will learn what’s the Top-level statements involved in C# 9.0.
Prerequisite
- You’ll need to set up your machine to run .NET 5, which includes the C# 9 compiler.
Top-level Statements
Top-level Statement is one of the wonderful new features introduced by C# 9.0
We have created a hello world program in the first C# tutorial #1 C# Hello World with .NET CLI , the entry method is Main method which is included in Program class.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Starting in C# 9, you don’t have to explicitly include a Main method in a console application project. Instead, you can use the top-level statements feature to minimize the code you have to write. In this case, the compiler generates a class and Main method entry point for the application.
Here’s a Program.cs file that is a complete C# program in C# 9:
using System;
Console.WriteLine("Hello World!");
Only two lines of code, that is cool!
So, what’s the top-level statements? It is the code statements that do not wrap in a class, and these code been wrote in a file which let’s call it top-level statements file.
Key Points
- An application must have only one entry point, so a project can have only one file with top-level statements;
- You can write a
Mainmethod explicitly in top-level statements file, but it can’t function as an entry point. - In a project with top-level statements, you can’t use the
-maincompiler option to select the entry point, even if the project has one or moreMainmethods. - Using directives must come first in the file.
- Top-level statements are implicitly in the global namespace.
- Namespaces and type definitions must come after the top-level statements.
- Top-level statements can reference the
argsvariable to access any command-line arguments that were entered. Theargsvariable is never null but itsLengthis zero if no command-line arguments were provided.
Top-level Statements Sample
Following is the sample for showing how to define and use method, class in the top-level statements file, in our case it is Program.cs .
using System;
using Test;
Console.WriteLine("Hello top-level statements !");
if (args.Length > 0)
{
Console.WriteLine("Arguments: ");
foreach (var arg in args)
{
Console.Write($" {arg} ");
}
}
else
{
Console.WriteLine("No arguments");
}
Console.WriteLine();
TestClass test = new TestClass();
test.TestOne();
TestTwo();
void TestTwo()
{
Console.WriteLine("This is TestTwo method. under global namespace.");
}
namespace Test
{
class TestClass
{
public void TestOne()
{
Console.WriteLine("This is TestOne method in TestClass under Test namespace.");
}
}
}
2 Replies to “#3 – C# 9.0 Top-level Statements”