Lesson 1 · ~8 min
Hello World in C#
Write your first line of C#, understand what it does, and learn why you'll meet two different shapes of C# program in the wild.
The smallest useful program
Since C# 9 (.NET 5+), a program can be just statements at the top of the file — no class, no Main. This is what dotnet new console gives you today:
Console.WriteLine("Hello, world!");
Console.WriteLine prints its argument and moves to the next line. Console.Write prints without the newline — run this and watch the two calls share one line:
Console.Write("C# is");
Console.WriteLine("one line");
Comments
Two styles, same as C++ and Java. Comments are for the next reader (often you, three weeks later):
// A single-line comment — everything after // is ignored.
/* A block comment
can span several lines. */
Console.WriteLine("comments are ignored"); // this part too
The classic template: class Program + Main
Older tutorials, textbooks and a lot of production code use the classic shape. It is not obsolete — it's what you'll see in most jobs. Both shapes mean the same thing: find the entry point, run it.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello from Main!");
}
}
Piece by piece:
using System;— imports the standard namespace so you can writeConsoleinstead ofSystem.Console. (Our browser engine lets you omit it.)class Program— a named container for your code. C# is fully object-oriented: all code lives in types.static void Main(string[] args)— the entry point.staticmeans it runs without creating an object first;voidmeans it returns nothing;argsholds command-line arguments.
Your first input
Programs get interesting when they react. Console.ReadLine() reads one line of text — type into the input box below the code before running:
Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
Two new ideas in three lines:
string name = Console.ReadLine();— declares a variable of typestringand stores the input in it.$"Hello, {name}!"— an interpolated string: everything inside{…}is an expression, evaluated and inserted. This is the idiomatic way to build text in modern C#.
Practice right now
Open the playground and change the program to print two lines: your name, then your favorite number. When you're comfortable, the natural next step is the first judged problem: Sum of Two Numbers.