C#C#
AdvancedLesson 13 of 16

Interfaces & Generics – C#

Define contracts and write type-safe, reusable code.

An interface describes what a type can do without specifying how. Classes and records implement any number of interfaces. This lets you program against abstractions – the basis for testability and dependency injection.

var warenkorb = new List<IPreis>
{
    new Buch("C# Book", 30m),
    new Kaffee("Espresso", 4m)
};
Console.WriteLine(Gesamt(warenkorb));   // 34

static decimal Gesamt(IEnumerable<IPreis> items) => items.Sum(i => i.Preis);

interface IPreis { decimal Preis { get; } }
record Buch(string Titel, decimal Preis) : IPreis;
record Kaffee(string Sorte, decimal Preis) : IPreis;

Generics (<T>) make classes and methods usable for arbitrary types – type-safe and without casts. With where you restrict the allowed types.

var stapel = new Stapel<string>();
stapel.Push("a");
stapel.Push("b");
Console.WriteLine(stapel.Pop());      // b
Console.WriteLine(stapel.Anzahl);     // 1

Console.WriteLine(Groesster(3, 7));                 // 7
Console.WriteLine(Groesster("apple", "pear"));     // pear

static T Groesster<T>(T a, T b) where T : IComparable<T>
    => a.CompareTo(b) >= 0 ? a : b;

class Stapel<T>
{
    private readonly List<T> _items = new();
    public void Push(T item) => _items.Add(item);
    public T Pop()
    {
        var letztes = _items[^1];
        _items.RemoveAt(_items.Count - 1);
        return letztes;
    }
    public int Anzahl => _items.Count;
}

Since .NET 7 there is "generic math": interfaces such as INumber<T> allow algorithms that work for all numeric types (T.Zero, +, * on T).

Console.WriteLine(Summe(new[] { 1, 2, 3 }));       // 6
Console.WriteLine(Summe(new long[] { 10, 20 }));    // 30

static T Summe<T>(IEnumerable<T> werte) where T : System.Numerics.INumber<T>
{
    T s = T.Zero;
    foreach (var w in werte) s += w;
    return s;
}
TipCommon constraints: where T : class (reference type), struct (value type), new() (parameterless constructor), IComparable<T> or your own interface. Abstract classes (abstract), unlike interfaces, can also share state and implementation.