0
0
C Sharp (C#)programming~5 mins

Top-level statements in modern C#

Choose your learning style9 modes available
Introduction

Top-level statements let you write simple C# programs without needing to write extra code like class or Main method. It makes your code shorter and easier to read.

When you want to quickly test a small piece of code without boilerplate.
When writing simple console apps or scripts.
When teaching beginners to focus on logic, not structure.
When creating quick prototypes or demos.
When you want cleaner code for small programs.
Syntax
C Sharp (C#)
using System;

Console.WriteLine("Hello, world!");
You do not need to write a class or Main method.
The compiler automatically creates the Main method behind the scenes.
Examples
A simple program that prints a message without any class or method.
C Sharp (C#)
Console.WriteLine("Welcome to C# top-level statements!");
You can declare variables and use them directly at the top level.
C Sharp (C#)
int x = 5;
int y = 10;
Console.WriteLine($"Sum is {x + y}");
You can include using directives at the top before statements.
C Sharp (C#)
using System;

var now = DateTime.Now;
Console.WriteLine($"Current time: {now}");
Sample Program

This program asks for your name and then greets you. It uses top-level statements so no class or Main method is needed.

C Sharp (C#)
using System;

Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
OutputSuccess
Important Notes

Top-level statements are supported starting from C# 9.0 and later.

You can still use classes and methods if your program grows bigger.

Only one file in the project can have top-level statements.

Summary

Top-level statements simplify small C# programs by removing boilerplate.

They let you write code directly without class or Main method.

Great for beginners, quick tests, and simple apps.