C#: More snippets – code examples
Method with default value
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
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
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
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
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
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
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)
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
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
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.