Top-Level Statements
Top-level statements are a modern C# feature introduced in C# 9
that allows developers to write executable code directly in a
C# file without explicitly creating a Program class
and Main() method.
This feature reduces boilerplate code and makes small applications, learning programs, scripts, and simple utilities easier to write.
Traditional C# Program Structure
Traditionally, a C# console application contains a
Program class and a Main() method.
using System;
class Program
{
static void Main()
{
Console.WriteLine("WelCome To CIIT Training Institute π€π¨βπ« ...!");
}
}
Output
WelCome To CIIT Training Institute π€π¨βπ« ...!
Basic Top-Level Statement
Using top-level statements, the same program can be written much more simply.
Console.WriteLine("WelCome To CIIT Training Institute π€π¨βπ« ...!");
Output
WelCome To CIIT Training Institute π€π¨βπ« ...!
There is no need to explicitly write the Program
class or Main() method.
Using Variables
You can declare variables directly in a top-level statement file.
using System;
class Program
{
static void Main()
{
string name = "Rahul";
int age = 25;
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
}
}
Output
Name: Rahul
Age: 25
Using Methods with Top-Level Statements
Methods can also be declared in a file containing top-level statements. Local functions are commonly used for small operations.
using System;
int Add(int a, int b)
{
return a + b;
}
int result = Add(10, 20);
Console.WriteLine(result);
Output
30
Statements Allowed in Top-Level Code
You can use normal C# statements directly in a top-level program.
using System;
int marks = 82;
if (marks >= 75)
{
Console.WriteLine("Distinction");
}
else
{
Console.WriteLine("Pass");
}
Output
Distinction
Using Loops
Loops can also be written directly without a
Program class.
using System;
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Number: {i}");
}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Using Directives
Namespace imports can be placed before the top-level statements.
using System;
using System.Text;
StringBuilder builder = new StringBuilder();
builder.Append("CIIT ");
builder.Append("Trainingπ€");
Console.WriteLine(builder.ToString());
Output
CIIT Trainingπ€
Command-Line Arguments
Top-level programs can access command-line arguments through
the automatically available args variable.
using System;
Console.WriteLine($"Arguments count: {args.Length}");
foreach (string argument in args)
{
Console.WriteLine(argument);
}
The args variable contains values passed to the
application when it starts.
Returning an Exit Code
A top-level program can return an integer exit code. This is useful when a command-line application needs to report success or failure to the operating system.
Console.WriteLine("CIIT Student Application completed successfully π©..");
return 0;
0 commonly represents successful
execution, while a non-zero value can indicate an error.
Rules and Restrictions
- Top-level statements must appear before type declarations such as classes and records.
- A project should have only one file containing top-level statements as its entry point.
- The compiler generates the entry-point structure automatically.
- You should not manually define another entry point for the same application.
- Top-level statements are mainly useful for applications where a simplified entry point improves readability.
What Happens Behind the Scenes?
Although the developer does not explicitly write the
Program class and Main() method,
the compiler creates the required entry-point structure.
Console.WriteLine("WelCome To CIIT Training Institute π€π¨βπ« ...!");
class Program
{
static void Main()
{
Console.WriteLine("WelCome To CIIT Training Institute π€π¨βπ« ...!");
}
}
Traditional Program vs Top-Level Statements
| Traditional Program | Top-Level Statements |
|---|---|
| Requires explicit Program class | Program class is generated automatically |
| Requires explicit Main method | No need to write Main method |
| More boilerplate code | Less boilerplate code |
| Useful for explicit application structure | Useful for simple entry-point code |
| Common in older C# applications | Common in modern .NET templates |
Top-Level Statements in ASP.NET Core
Modern ASP.NET Core applications commonly use top-level statements
in Program.cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
This approach keeps the application startup configuration concise while still allowing dependency injection, middleware configuration, routing, authentication, and other ASP.NET Core features.
Program.cs.
Understanding this syntax is important for real-world .NET development.
When Should You Use Top-Level Statements?
- Console applications.
- Small utilities and tools.
- Learning and demonstration programs.
- Simple command-line applications.
- Modern ASP.NET Core application startup.
- Projects where reducing boilerplate improves readability.
Common Mistakes
- Creating another Main method unnecessarily.
- Placing top-level statements after a class declaration.
- Thinking that the Program class does not exist internally.
- Using top-level statements for a large application when an explicit structure may be easier to maintain.
Best Practices
- Keep top-level code short and readable.
- Move reusable business logic into classes and services.
- Use dependency injection in ASP.NET Core applications.
- Avoid putting the complete application logic into Program.cs.
- Use top-level statements mainly for application startup and simple entry-point logic.
Interview Questions
- What are top-level statements in C#?
- In which version of C# were top-level statements introduced?
- Why are top-level statements useful?
- What happens to the Program class when using top-level statements?
- Can we have multiple top-level statement files in one application?
- What is the purpose of the
argsvariable? - Can top-level statements return an exit code?
- Where are top-level statements commonly used in ASP.NET Core?
- What are the limitations of top-level statements?
- What is the difference between traditional Main method and top-level statements?
Practice Programs
- Create a console application using top-level statements that prints your name, course, and institute.
- Create a calculator using top-level statements.
- Create a program that calculates a student's grade.
- Create a program that accepts command-line arguments and displays them.
- Create a program using a local function to calculate the factorial of a number.
- Create a simple ASP.NET Core Program.cs using top-level statements.
Summary
- Top-level statements simplify the entry point of a C# application.
- They remove the need to explicitly write the Program class.
- They remove the need to explicitly write the Main method.
- Normal C# statements can be written directly in the file.
-
The
argsvariable provides access to command-line arguments. - Top-level programs can return an exit code.
- Modern ASP.NET Core applications commonly use this approach in Program.cs.
- Top-level statements reduce boilerplate while keeping application startup code concise and readable.