C#C#

C#: More snippets – code examples

Contents

Method with default value

Functions#method#function#parameter#lambdaCompare in all languages
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
Console.WriteLine(Begruesse("Ada"));
Console.WriteLine(Begruesse("Linus", gruss: "Hi"));

static string Begruesse(string name, string gruss = "Hello")
    => $"{gruss}, {name}!";

Parameters with a default value are optional; named arguments (gruss: ...) make calls readable. => writes a single-expression method.

Class with inheritance

OOP#class#oop#inheritance#overrideCompare in all languages
Use case: Bundle data and behavior, e.g. users, products, game characters.
Console.WriteLine(new Hund("Rex").Sprich());

class Tier(string name)
{
    public string Name { get; } = name;
    public virtual string Sprich() => $"{Name} makes a sound";
}

class Hund(string name) : Tier(name)
{
    public override string Sprich() => $"{Name} says Woof!";
}

Hund inherits from Tier and overrides the virtual method with override. The primary constructors (C# 12) save the classic constructor.

Record with with-expression

OOP#record#with#immutability#equality
Use case: Copy immutable data objects and change individual fields (DTOs, configurations).
var a = new Produkt("Coffee", 4);
var b = a with { Preis = 5 };
Console.WriteLine(a);                            // Produkt { Name = Coffee, Preis = 4 }
Console.WriteLine(b);                            // Produkt { Name = Coffee, Preis = 5 }
Console.WriteLine(a == new Produkt("Coffee", 4)); // True

record Produkt(string Name, int Preis);

Records compare by value; with creates a copy with changed properties, and the original stays unchanged.

try / catch / finally

Error handling#try#catch#exception#finallyCompare in all languages
Use case: Guard user input or network access without the program crashing.
try
{
    int zahl = int.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine("Invalid: " + e.Message);
}
finally
{
    Console.WriteLine("Cleanup");
}

finally always runs – ideal for closing resources. Catch specific exception types such as FormatException.

Handle null safely

Error handling#null#nullable#operators
Use case: Process optional values (search results, missing fields) without a NullReferenceException.
string? eingabe = null;
Console.WriteLine(eingabe?.ToUpper() ?? "no input");   // no input

eingabe ??= "ada";
Console.WriteLine(eingabe.ToUpper());                       // ADA

string[] namen = { "Ada", "Bob" };
string? treffer = namen.FirstOrDefault(n => n.StartsWith('C'));
Console.WriteLine(treffer is null ? "no match" : treffer);

?. short-circuits on null, ?? provides a fallback value, ??= assigns only if null. FirstOrDefault returns null for reference types.

Read and write a file

Files#file#io#file-ioCompare in all languages
Use case: Save and load logs, configurations or text data.
File.WriteAllText("notizen.txt", "Line 1\nLine 2\n");

foreach (string zeile in File.ReadLines("notizen.txt"))
{
    Console.WriteLine(zeile);
}

File.WriteAllText writes the whole file, File.ReadLines reads it line by line in a memory-friendly way. File lives in System.IO (imported automatically via implicit usings).

Read and write JSON

Files#json#serialization#records
Use case: Exchange data with web APIs or other programs, save configurations.
using System.Text.Json;

var nutzer = new Nutzer("Ada", ["Python", "Go"]);
string text = JsonSerializer.Serialize(nutzer, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(text);

Nutzer? zurueck = JsonSerializer.Deserialize<Nutzer>(text);
Console.WriteLine(zurueck?.Sprachen[0]);   // Python

record Nutzer(string Name, string[] Sprachen);

System.Text.Json is part of the framework. Serialize converts objects to JSON, Deserialize<T> converts back; the result can be null, hence Nutzer?.

HTTP request (HttpClient)

Networking#http#httpclient#api#async
Use case: Fetch data from a web API.
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("ProgrammAtlas");
string json = await client.GetStringAsync("https://api.github.com/repos/dotnet/runtime");

using var doc = JsonDocument.Parse(json);
Console.WriteLine(doc.RootElement.GetProperty("full_name").GetString());
Console.WriteLine(doc.RootElement.GetProperty("stargazers_count").GetInt32());

GetStringAsync throws an HttpRequestException on HTTP errors. The GitHub API requires a User-Agent. Reuse the HttpClient when making multiple calls.

Run tasks in parallel with Task.WhenAll

Concurrency#task#whenall#async#parallel
Use case: Complete several slow I/O tasks (API calls, downloads) at the same time.
var tasks = Enumerable.Range(1, 4).Select(BerechneAsync);
int[] ergebnisse = await Task.WhenAll(tasks);
Console.WriteLine(string.Join(", ", ergebnisse));   // 1, 4, 9, 16

static async Task<int> BerechneAsync(int n)
{
    await Task.Delay(500);
    return n * n;
}

All four tasks wait at the same time, so the total duration is about 0.5 s instead of 2 s. WhenAll returns the results in the order of the tasks.

Command-line arguments

Tools#cli#args#command-line
Use case: Build your own CLI tools with parameters.
if (args.Length == 0)
{
    Console.WriteLine("Aufruf: dotnet run -- <Name> [--laut]");
    return;
}

string text = $"Hello {args[0]}";
Console.WriteLine(args.Contains("--laut") ? text.ToUpper() : text);

In top-level programs the variable args exists automatically. Call it e.g. with dotnet run -- Ada --laut. For complex CLIs there is the System.CommandLine library.