Hello World in C# — Top-Level Statements and Console Output Explained
In this tutorial, you will learn about Hello World in C#. We cover key concepts, practical examples, and best practices to help you master this topic.
The classic Hello World program in C# demonstrates top-level statements, the Console class for input and output, implicit usings, and the .NET build system in just a few lines of code.
What You'll Learn
You will dissect every line of a modern C# Hello World program, understand top-level statements introduced in C# 9, use Console.WriteLine and Console.ReadLine for console I/O, learn how the compiler generates the Main method implicitly, and compile and run your program with the dotnet CLI.
Why It Matters
Hello World is the traditional first program because it validates your entire development toolchain. In C#, it also introduces important concepts: how the compiler handles entry points, how namespaces are resolved via implicit usings, and how the .NET runtime manages output. Understanding this program deeply makes subsequent lessons easier.
Real-World Use
Console applications are used for CLI tools, build scripts, data processing pipelines, and backend services. The Console class is also the foundation for logging in many applications before they adopt structured logging frameworks like Serilog or NLog.
Learning Path
graph LR
A["02: Installing .NET"] --> B["03: Hello World"]
B --> C["04: Variables & Types"]
C --> D["05: Built-in Types"]
D --> E["06: Operators"]
style A fill:#4a90d9,stroke:#2c5f8a,color:#fff
style B fill:#4a90d9,stroke:#2c5f8a,color:#fff
style C fill:#4a90d9,stroke:#2c5f8a,color:#fff
style D fill:#4a90d9,stroke:#2c5f8a,color:#fff
style E fill:#4a90d9,stroke:#2c5f8a,color:#fff
The Program
Modern C# (9+) uses top-level statements:
Console.WriteLine("Hello, World!");
Save this as Program.cs, then run:
dotnet new console -n Hello --force
# Replace Program.cs with the line above
dotnet run
Expected output:
Hello, World!
How Top-Level Statements Work
Before C# 9, every program needed an explicit Main method:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
With top-level statements (C# 9+), the compiler auto-generates the class and Main method. Your code becomes the body of the generated Main method. This reduces boilerplate and lets you focus on logic.
The compiler generates something equivalent to:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
The implicit usings (from <ImplicitUsings>enable</ImplicitUsings> in the .csproj) automatically add common namespaces.
Console Class Methods
The Console class provides several methods for I/O:
// Output
Console.WriteLine("Prints with newline");
Console.Write("Prints without newline");
Console.WriteLine($"Formatted: {42}");
// Input
string name = Console.ReadLine();
int key = Console.Read(); // Reads a single character as int
// Error output
Console.Error.WriteLine("Error message");
// Formatting
Console.WriteLine("Name: {0}, Age: {1}", "Alice", 30);
Reading User Input
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = int.Parse(ageInput);
Console.WriteLine($"Hello, {name}! You are {age} years old.");
Compile and run:
dotnet run
Expected output:
Enter your name: Alice
Enter your age: 25
Hello, Alice! You are 25 years old.
Command Line Arguments
Top-level statements have access to args implicitly:
Console.WriteLine($"Number of arguments: {args.Length}");
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"args[{i}] = {args[i]}");
}
Run with arguments:
dotnet run -- first second third
Expected output:
Number of arguments: 3
args[0] = first
args[1] = second
args[2] = third
Understanding the Compilation Pipeline
# Compile only (no run)
dotnet build
# Compile with verbose output
dotnet build -v normal
# See the generated IL
dotnet build && ildasm bin/Debug/net8.0/Hello.dll
The compiler (Roslyn) performs:
- Parsing: Converts source text into syntax trees
- Binding: Resolves types, methods, and members
- Emitting: Generates IL assembly and metadata
- Linking: Produces the final executable or library
ASCII Art Output
Console.WriteLine(" * ");
Console.WriteLine(" *** ");
Console.WriteLine("*****");
Console.WriteLine(" | ");
Expected output:
*
***
*****
|
Common Mistakes
Mistake 1: Multiple Top-Level Statement Files
Only one file in a project can use top-level statements. Having Program.cs with top-level statements and another .cs file with them causes compilation error CS8803.
Mistake 2: Not Using $ for Interpolation
Console.WriteLine("Hello, {name}") prints the literal {name} instead of the variable value. Use $"Hello, {name}" for string interpolation.
Mistake 3: Forgetting using for Non-Implicit Namespaces
While System is included via implicit usings, other namespaces like System.Text.Json or System.Net.Http require explicit using directives.
Mistake 4: Expecting Console.ReadLine to Parse Automatically
Console.ReadLine always returns a string. You must explicitly parse to other types with int.Parse(), double.Parse(), or Convert.ToInt32().
Mistake 5: Using Console.Read Instead of Console.ReadLine
Console.Read() returns the ASCII code of the first character, not the full string. Use Console.ReadLine() for text input.
Practice Questions
- What is the difference between
Console.WriteandConsole.WriteLine? - How do top-level statements work? What does the compiler generate?
- Write a program that asks for the user's favorite color and prints a response.
- What are the implicit usings that modern .NET projects include?
- How do you access command-line arguments in a top-level statement program?
Challenge
Write a program that accepts a name and age from command-line arguments, validates that both are provided, and prints a personalized greeting. If arguments are missing, prompt the user to input them interactively.
FAQ
Mini Project
Create an interactive quiz program:
Console.WriteLine("=== Quick Quiz ===\n");
Console.Write("What is the capital of France? ");
string answer1 = Console.ReadLine();
bool correct1 = answer1.Trim().ToLower() == "paris";
Console.WriteLine(correct1 ? "Correct!" : "Wrong! The answer is Paris.\n");
Console.Write("What is 12 * 8? ");
string answer2 = Console.ReadLine();
bool correct2 = answer2.Trim() == "96";
Console.WriteLine(correct2 ? "Correct!" : "Wrong! The answer is 96.\n");
Console.Write("Is C# compiled or interpreted? ");
string answer3 = Console.ReadLine();
bool correct3 = answer3.Trim().ToLower().Contains("compil");
Console.WriteLine(correct3 ? "Correct!" : "Wrong! C# is compiled to IL.\n");
int score = (correct1 ? 1 : 0) + (correct2 ? 1 : 0) + (correct3 ? 1 : 0);
Console.WriteLine($"Your score: {score}/3");
Expected output:
=== Quick Quiz ===
What is the capital of France? Paris
Correct!
What is 12 * 8? 96
Correct!
Is C# compiled or interpreted? compiled
Correct!
Your score: 3/3
What's Next
You have written and understood your first C# program. The next lesson covers variables, types, the difference between value and reference types, and the var keyword.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro