C#C#

C#: Advanced – code examples

Contents

Iterator with yield return

Advanced#yield#iterator#ienumerable
Use case: Produce large or infinite sequences piece by piece without holding everything in memory.
foreach (int f in Fibonacci().Take(10))
    Console.Write(f + " ");   // 0 1 1 2 3 5 8 13 21 34
Console.WriteLine();

static IEnumerable<int> Fibonacci()
{
    int a = 0, b = 1;
    while (true)
    {
        yield return a;
        (a, b) = (b, a + b);
    }
}

yield return delivers values on demand; the method pauses in between. Take(10) ends the actually infinite sequence.

Extension method

Advanced#extension#static#linq
Use case: Add your own helper methods to existing types without modifying them.
Console.WriteLine("Anna".IstPalindrom());     // True
Console.WriteLine("Python".IstPalindrom());   // False

static class StringErweiterungen
{
    public static bool IstPalindrom(this string s)
    {
        var t = s.ToLower();
        return t == new string(t.Reverse().ToArray());
    }
}

A static class with this before the first parameter makes the method callable on all strings – this is how LINQ works, too.

Event publisher and subscriber

Advanced#event#delegate#observer
Use case: Decouple components: one object reports changes, others react (UI, logging, notifications).
var btn = new Knopf();
btn.Geklickt += n => Console.WriteLine($"Click No. {n}");
btn.Klicke();
btn.Klicke();

class Knopf
{
    private int _zaehler;
    public event Action<int>? Geklickt;
    public void Klicke() => Geklickt?.Invoke(++_zaehler);
}

event allows outsiders only +=/-=, while raising the event stays reserved for the class. Output: Click No. 1, Click No. 2.

Generic class and constraint

Advanced#generics#constraint#where
Use case: Write reusable containers or repositories for different types.
var zahlen = new Ergebnis<int>(42);
var text = new Ergebnis<string>("ok");
Console.WriteLine($"{zahlen.Wert} {text.Wert}");   // 42 ok
Console.WriteLine(Groesster(3, 9));                // 9

record Ergebnis<T>(T Wert);

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

<T> makes the type and method generic; where T : IComparable<T> guarantees that CompareTo exists.

using and IDisposable

Advanced#using#idisposable#resources
Use case: Reliably release files, database connections and locks.
using (var abschnitt = new Abschnitt("Calculation"))
{
    Console.WriteLine(2 + 2);
}

class Abschnitt : IDisposable
{
    private readonly string _name;
    public Abschnitt(string name) => _name = name;
    public void Dispose() => Console.WriteLine($"{_name} beendet");
}

using calls Dispose() at the end of the block – even when exceptions occur. Output: 4, then "Calculation finished".