IntermediateLesson 7 of 16
Classes, Inheritance & Records – C#
Custom data types with properties, behavior and value semantics.
A class bundles data (fields/properties) and behavior (methods). Properties ({ get; set; }) are the C# way instead of writing your own getter methods. virtual/override enable polymorphism, and base calls the constructor of the base class.
Tier[] tiere = { new Tier("Something"), new Hund("Rex") };
foreach (var t in tiere)
Console.WriteLine(t.Sprich());
class Tier
{
public string Name { get; }
public Tier(string name) { Name = name; }
public virtual string Sprich() => $"{Name} makes a sound";
}
class Hund : Tier
{
public Hund(string name) : base(name) { }
public override string Sprich() => $"{Name} says Woof!";
}Records are classes for pure data: value-based equality, a nice ToString output and non-destructive copies with with. Ideal for DTOs and immutable models.
var p1 = new Punkt(3, 4);
var p2 = p1 with { Y = 10 };
Console.WriteLine(p1); // Punkt { X = 3, Y = 4 }
Console.WriteLine(p2); // Punkt { X = 3, Y = 10 }
Console.WriteLine(p1 == new Punkt(3, 4)); // True
record Punkt(int X, int Y);With init (settable only during creation), required (mandatory member) and private set you control who may change properties – this is how a class protects its invariants:
var konto = new Konto { Inhaber = "Ada" };
konto.Einzahlen(50);
Console.WriteLine($"{konto.Inhaber}: {konto.Saldo}"); // Ada: 50
class Konto
{
public required string Inhaber { get; init; }
public decimal Saldo { get; private set; }
public void Einzahlen(decimal betrag)
{
if (betrag <= 0) throw new ArgumentOutOfRangeException(nameof(betrag));
Saldo += betrag;
}
}TipRule of thumb:
class for objects with identity and behavior (services, entities), record for data with value equality, struct for very small value types.