C#: Basics – code examples
Hello World
Use case: A first test of whether the SDK and project work.
Console.WriteLine("Hello World!");Thanks to top-level statements, a single line is enough – no class and no Main needed.
Variables and types
Use case: Store values and check their type.
string name = "Ada";
int alter = 36;
double groesse = 1.68;
bool aktiv = true;
Console.WriteLine($"{name} {alter} {aktiv}");
Console.WriteLine($"{alter.GetType().Name} {groesse.GetType().Name}");Types come before the name (or var for type inference); $"..." interpolates values into text.
Date and time
Basics#datetime#time#date#timespan
Use case: Calculate deadlines, format timestamps.
var jetzt = new DateTime(2026, 3, 15, 9, 30, 0);
Console.WriteLine(jetzt.ToString("dd.MM.yyyy HH:mm")); // 15.03.2026 09:30
Console.WriteLine(jetzt.AddDays(30).ToString("dd.MM.yyyy")); // 14.04.2026
int tage = (new DateTime(2026, 12, 24) - jetzt).Days;
Console.WriteLine($"{tage} days until Christmas"); // 283The difference between two DateTime values is a TimeSpan; AddDays and the like return new values (DateTime is immutable). Use DateTimeOffset for time zones.
Enum
Basics#enum#enumeration
Use case: Represent fixed sets of choices in a type-safe way (weekdays, statuses, roles).
var tag = Wochentag.Sa;
Console.WriteLine(tag); // Sa
Console.WriteLine((int)tag); // 5
Console.WriteLine(Enum.Parse<Wochentag>("Mo")); // Mo
Console.WriteLine(Enum.GetNames<Wochentag>().Length); // 7
enum Wochentag { Mo, Di, Mi, Do, Fr, Sa, So }Enums count from 0 by default and can be converted to numbers. Enum.Parse<T> converts text (throws on an invalid name), Enum.TryParse is the safe variant.