Skip to content
LumenaryAcademy
Foundations 50 min

First steps with C# and .NET

Where C# came from, what .NET is, and your first programs as single files and as projects.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Why learn C#?

Suppose you want to build a web service that a mobile app calls, a desktop tool for a clinic's front desk, a game that runs on phones and consoles, or a command-line utility that cleans up a messy folder of invoices. You could write each of these in a different language. Many teams write all four in C#.

C# is a general-purpose, statically typed language. Statically typed means the compiler knows the type of every variable before the program runs, so a whole class of mistakes (adding a date to a name, calling a method that does not exist) is caught while you type rather than at three in the morning in production. It runs on .NET, a free, open-source runtime and library that works on Windows, macOS and Linux, on x64 and Arm processors, in containers and in the browser through WebAssembly.

What C# is used for, in practice:

  • Web services and APIs, with ASP.NET Core, a fast, widely deployed web framework.
  • Cloud and enterprise systems: banks, airlines, hospitals, logistics and governments run large C# codebases.
  • Games: the Unity engine uses C# for game logic, and the Godot engine supports it too.
  • Desktop applications on Windows, and cross-platform ones with frameworks such as .NET MAUI or Avalonia.
  • Tools: build systems, editors, test runners, and the C# compiler itself, which is written in C#.

C# is a good language to know well because it sits in the middle of several worlds. It has the classes and interfaces of Java, the value types and low-level control of C and C++ when you need them, and a steady stream of ideas from functional languages: lambdas, LINQ queries, records, pattern matching. Learn it carefully and you will find much of it familiar in other languages, and much of other languages familiar in it.

History & global context

From a research project to C# 14

C# was designed at Microsoft by a team led by Anders Hejlsberg, who had earlier written Turbo Pascal and led the design of Delphi (and who later led the design of TypeScript). Microsoft announced the language in 2000 alongside the .NET Framework, and version 1.0 shipped in 2002 with Visual Studio .NET. From the start it was standardised: Ecma International published the first edition of the C# standard, ECMA-334, in December 2001, and ISO followed.

The early language looked a lot like Java: classes, single inheritance, interfaces, garbage collection. But it differed in ways that still matter. It had value types (struct) that live inline rather than as separate objects, properties and events as part of the language, and a way to call native code directly. Its history since then is a series of big ideas, each arriving with a version of the platform:

VersionYearHeadline additions
C# 22005Generics, nullable value types, iterators (yield return)
C# 32007Lambdas, var, LINQ query expressions, extension methods
C# 52012async and await
C# 62015String interpolation; the new open-source compiler, Roslyn
C# 72017Tuples, the first pattern matching
C# 82019Nullable reference types, switch expressions
C# 92020Records, top-level statements
C# 122023Primary constructors, collection expressions
C# 142025Extension members, the field keyword, null-conditional assignment

Just as important as the language is the platform's history. The original .NET Framework ran only on Windows. In 2014 Microsoft began open-sourcing .NET, and in 2016 shipped .NET Core, a cross-platform rewrite developed on GitHub. In 2020 the two lines were unified as plain .NET 5, and since then a new version has shipped every November. Even-numbered releases are long-term support (LTS, three years of fixes); odd-numbered ones are standard-term support (STS, two years). Each release brings a new C# version: .NET 10 (November 2025, LTS) brought C# 14, and .NET 11 (November 2026, STS) brought C# 15.

This course teaches C# 14 on .NET 10, because most teams build production systems on an LTS release. Where a newer feature is worth knowing about, the lesson says so and names its version.

Note

People still say "the .NET Framework" for the old Windows-only platform (versions 1.0 to 4.8.1, still supported and still running a great deal of software) and ".NET" or ".NET Core" for the modern one. New code should target modern .NET. If a job advertisement mentions .NET Framework 4.8, it usually means maintaining older systems.

IntuitionH

What happens when a C# program runs

When you run a C# program, two translations happen, at two different times.

First, the C# compiler (called Roslyn) reads your source code and checks it: every name must exist, every type must fit. If anything is wrong, you get an error and no program. If all is well, it does not produce machine code for your processor. It produces IL (intermediate language, sometimes called CIL or MSIL), a compact instruction set for an imaginary stack machine, packaged in a file called an assembly (a .dll, even for programs).

Second, when the program starts, the runtime (the CLR, the common language runtime) loads the assembly. As each method is called for the first time, the JIT compiler (just-in-time) translates its IL into real machine code for the processor in front of it, and from then on that machine code runs directly. The runtime also manages memory with a garbage collector, checks array bounds, and enforces type safety.

Definition— Assembly

The unit that the C# compiler produces and the .NET runtime loads: a .dll (or .exe) file containing IL code, metadata that describes every type and method, and references to other assemblies it needs.

Analogy, not a formal construction

Think of IL as sheet music and the JIT as a musician sight-reading it. The composer (the C# compiler) writes music that any trained musician can play. The musician (the runtime on each machine) turns it into sound for the instrument in their hands, whether that is an Intel laptop or an Arm phone.

Why two steps? Because one compiled assembly then runs on every operating system and processor .NET supports, and because the JIT can optimise for the exact machine it is on. Modern .NET even re-compiles hot methods with better optimisations once it has watched them run for a while (tiered compilation). When start-up time matters more than portability, for example for a small command-line tool or a cloud function, you can instead publish with Native AOT, which compiles everything ahead of time to a single native executable.

The other half of .NET is its base class library (BCL): thousands of ready-made types for text, numbers, dates, collections, files, networking, JSON, cryptography and threads. Console, string, List<int> and TimeOnly all come from there. Learning C# is half learning the language and half learning where things live in this library.

ComputationC

Installing .NET and running a single file

Install the .NET SDK (software development kit) from the official download page linked below; choose the latest .NET 10 SDK for your operating system. On Linux you can also use your distribution's package manager, and on macOS and Windows the installer is a normal package. The SDK includes the compiler, the runtime, the base class library and the dotnet command-line tool. Check that it worked:

bash
dotnet --version

It prints the SDK version, for example 10.0.404. (The runtime is what end users need to run a program; the SDK is what developers need to build one. The SDK contains a runtime.)

Your first program

Since .NET 10 you can run a C# program that is just one file, with no project around it. Create a file called hello.cs containing:

csharp
Console.WriteLine("Hello, world!");
Console.WriteLine("Habari, dunia!");

and run it from the same folder:

bash
dotnet run hello.cs

It prints:

text
Hello, world!
Habari, dunia!

The first run takes a few seconds because the SDK builds the program behind the scenes; later runs of the unchanged file reuse the build and start almost instantly. This is still a compiled program, not an interpreted script: the SDK creates a hidden project, compiles your file to an assembly and runs it.

Three things make such a short program possible:

  • Top-level statements (C# 9). A C# program normally starts in a method called Main inside a class. When the statements are written at the top level of one file, the compiler generates that class and method for you.
  • Implicit usings. Console lives in the System namespace, so its full name is System.Console. The SDK adds using System; and a handful of other common namespaces (collections, LINQ, files, tasks) automatically.
  • Semicolons and statements. Each statement ends with ;. Line breaks mean nothing to the compiler; the semicolons do.

A program with a little more in it

Here is a program that tells a team spread over five cities what time a 14:00 UTC call is for each of them:

csharp
// A first real program: one statement after another, top to bottom.
string[] cities = ["Nairobi", "Lagos", "Mumbai", "São Paulo", "Tokyo"];
double[] offsets = [3, 1, 5.5, -3, 9];

TimeOnly meetingUtc = new(14, 0);
Console.WriteLine($"The call starts at {meetingUtc:HH:mm} UTC.");

for (int i = 0; i < cities.Length; i++)
{
    TimeOnly local = meetingUtc.Add(TimeSpan.FromHours(offsets[i]));
    Console.WriteLine($"{cities[i],-10} {local:HH:mm}");
}

Console.WriteLine($"That is {cities.Length} cities.");

It prints:

text
The call starts at 14:00 UTC.
Nairobi    17:00
Lagos      15:00
Mumbai     19:30
São Paulo  11:00
Tokyo      23:00
That is 5 cities.

Read it line by line:

  • // ... is a comment, ignored by the compiler. (/* ... */ comments can span lines.)
  • string[] cities = [...] declares an array of strings and fills it with a collection expression, the square-bracket syntax added in C# 12. double[] holds floating-point numbers, so 5.5 (Mumbai is five and a half hours ahead of UTC) fits.
  • TimeOnly meetingUtc = new(14, 0); creates a time of day. When the type is written on the left, new(...) on the right does not need to repeat it.
  • $"..." is an interpolated string: expressions inside its braces are evaluated and inserted. After a colon comes a format (HH:mm means two-digit hours and minutes); after a comma comes an alignment (-10 means "pad to ten characters, left-aligned"), which is what lines the times up in a column.
  • The for loop has three parts: start (int i = 0), condition (i < cities.Length), and step (i++). Its body is the block in braces.
  • meetingUtc.Add(...) returns a new time. TimeOnly values never change; Add wraps around midnight, which is why a 14:00 call at UTC+9 shows as 23:00 rather than failing.

Types are .NET types

Every built-in C# type keyword is a short alias for a type in the base class library, and you can ask the runtime about any type with typeof. This program also shows that you can write a local function among top-level statements and call it:

csharp
// Every C# keyword type is an alias for a .NET type.
Console.WriteLine(typeof(int).FullName);
Console.WriteLine(typeof(string).FullName);
Console.WriteLine(typeof(double).FullName);

// Methods can live alongside top-level statements as local functions.
string Initials(string fullName)
{
    string result = "";
    foreach (string part in fullName.Split(' '))
    {
        result += part[0];
    }
    return result;
}

Console.WriteLine(Initials("Anders Hejlsberg"));
Console.WriteLine(Initials("Grace Brewster Murray Hopper"));

It prints:

text
System.Int32
System.String
System.Double
AH
GBMH

int is System.Int32, a 32-bit integer; string is System.String. The function Initials declares its parameter type (string fullName) and its return type (the string before its name). fullName.Split(' ') breaks the name at spaces into an array, foreach visits each piece, and part[0] is the first character, a char. Adding a char to a string with += appends it.

Worked examplesH

From one file to a project

Single files are perfect for learning, scripts and small tools. Real applications have many files, dependencies and settings, and live in a project. Create one with:

bash
dotnet new console -o Greeter
cd Greeter
dotnet run

dotnet new console creates a folder with a Program.cs (containing a top-level hello world) and a project file, Greeter.csproj:

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

The project file is read by MSBuild, .NET's build engine. OutputType says this builds a program rather than a library. TargetFramework says which .NET it runs on. ImplicitUsings turns on the automatic using lines you met above, and Nullable turns on nullable reference types, a safety feature you will study in a later lesson. Every .cs file in the folder (and its subfolders) is compiled into the project automatically.

The everyday commands are:

CommandWhat it does
dotnet new console -o NameCreate a new console project (also classlib, web, xunit and many more templates)
dotnet buildCompile the project to bin/Debug/net10.0/
dotnet runBuild if needed, then run
dotnet testBuild and run the tests in a test project
dotnet add package NameAdd a NuGet package (a library) to the project
dotnet publish -c ReleaseProduce the files you deploy

A single-file program can grow into a project without being rewritten. It can carry its own settings at the top, with directives that start with #:, for example a package it depends on:

csharp
#:package Humanizer@2.14.1

using Humanizer;

Console.WriteLine("file_based_apps_are_handy".Humanize());

When it outgrows one file, dotnet project convert hello.cs writes a project folder with an equivalent .csproj.

How professionals work

Most C# developers use an editor that understands the language deeply: Visual Studio on Windows, Visual Studio Code with Microsoft's C# Dev Kit extension on any system, or JetBrains Rider. All three use the compiler itself to show errors as you type, suggest fixes and refactor safely. Teams pin the SDK version in a global.json file so everyone builds with the same tools, run the same build in continuous integration, and upgrade from one LTS to the next every two years or so.

Common misconceptionsH

Common misconceptions

Misconception

"C# only runs on Windows." That was true of the .NET Framework. Modern .NET runs on Windows, macOS and Linux, and a large share of C# services in production run in Linux containers. Only some frameworks (Windows Forms and WPF, for desktop applications) are Windows-only.

Misconception

"C# is Microsoft's copy of Java." The two started close and have diverged for twenty years. C# has value types you define yourself, properties, generics that keep their type arguments at run time, LINQ, async/await (C# had it years before JavaScript and Python adopted the same idea), records and extensive pattern matching. Moving between the two is easy; treating one as the other leads to unidiomatic code.

Misconception

"dotnet run hello.cs interprets my script." No: it compiles the file to IL, caches the build, and runs it on the same runtime as any other .NET program. That is why the first run is slower than the next.

Misconception

"I need Visual Studio to write C#." You need only the SDK and a text editor. The dotnet command does everything an IDE does to build and run; the IDE makes it more pleasant.

Exercises

Exercises

Some of these ask what a program prints. Work it out on paper first, then check yourself by running the program with dotnet run.

1. First steps with C# and .NET

Warm-upHuman

When you build a C# program, what does the C# compiler write to disk?

Choose one

2. First steps with C# and .NET

Warm-upComputational

What does this program print?

Console.WriteLine(typeof(long).FullName);

3. First steps with C# and .NET

Warm-upHuman

You have a file report.cs containing top-level statements and no project file. With the .NET 10 SDK, which command builds and runs it?

Choose one

4. First steps with C# and .NET

CoreComputational

How many lines does this program print in total?

int count = 0;
for (int i = 1; i <= 10; i += 3)
{
    Console.WriteLine(i);
    count++;
}
Console.WriteLine($"Printed {count} numbers");

5. First steps with C# and .NET

CoreComputational

What does this program print?

TimeOnly start = new(22, 30);
TimeOnly later = start.Add(TimeSpan.FromHours(3));
Console.WriteLine($"{later:HH:mm}");

6. First steps with C# and .NET

CoreComputational

Using the lesson's Initials function (shown again below), what does the last line print?

string Initials(string fullName)
{
    string result = "";
    foreach (string part in fullName.Split(' '))
    {
        result += part[0];
    }
    return result;
}
Console.WriteLine(Initials("Ngozi Okonjo Iweala").ToLower());

7. First steps with C# and .NET

CoreHuman

A hospital is starting a new system in late 2026 that it expects to run, with security updates, for the next few years before its next planned upgrade. Which statements are true? (Choose all that apply.)

Choose all that apply

Further reading and resources

  • Download .NET · MicrosoftThe official SDK installers for Windows, macOS and Linux.
  • File-based apps · MicrosoftThe reference for running a single .cs file and for the directives it can carry.
  • The history of C# · MicrosoftWhat arrived in each version of the language.
  • .NET release policies · MicrosoftHow long each release is supported, and what LTS and STS mean.
  • dotnet/roslynThe open-source C# and Visual Basic compilers.