Beginner

Hello World in C#

Your first C# program - the classic Hello World example with Docker setup

Every programming journey starts with Hello World. Let’s write our first C# program.

The Code

Create a file named Program.cs:

1
Console.WriteLine("Hello, World!");

Yes, that’s it! Modern C# (9.0+) supports top-level statements, so you don’t need all the boilerplate that older tutorials show. The compiler automatically wraps this in a Main method for you.

Understanding the Code

  • Console.WriteLine() - Writes text to the console followed by a newline
  • Top-level statements - C# 9+ allows simple programs without explicit class/method declarations

Traditional Version

If you’re curious, here’s what older C# code (pre-9.0) looks like:

1
2
3
4
5
6
7
8
9
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}

Both versions produce identical output. The modern version is just cleaner for simple programs.

Running with Docker

The easiest way to run C# without installing the .NET SDK locally:

1
2
3
4
5
# Pull the official .NET SDK image
docker pull mcr.microsoft.com/dotnet/sdk:9.0

# Run the program (creates a temporary project)
docker run --rm -v $(pwd):/app -w /app mcr.microsoft.com/dotnet/sdk:9.0 sh -c "dotnet new console -o . --force >/dev/null 2>&1 && dotnet run"

The command creates a temporary project file, compiles your Program.cs, and runs it.

Running Locally

If you have the .NET SDK installed (version 6.0+):

1
2
3
4
# Create a new project and run
dotnet new console -o HelloWorld
# Replace the generated Program.cs with your code
dotnet run --project HelloWorld

Expected Output

Hello, World!

Key Concepts

  1. C# is compiled - Source code is compiled to Intermediate Language (IL)
  2. IL runs on the CLR - Common Language Runtime executes the bytecode
  3. Top-level statements - Modern C# allows simple programs without ceremony
  4. Console is in System - The System namespace is implicitly imported in modern C#

.NET SDK vs Runtime

  • SDK: For development - includes compiler, libraries, and CLI tools
  • Runtime: For running apps only - smaller, production-focused

We use the SDK image for development because we need to compile the code.

Next Steps

Continue to Variables and Data Types to learn about storing and manipulating data in C#.

Running Today

All examples can be run using Docker:

docker pull mcr.microsoft.com/dotnet/sdk:9.0
Last updated: