Skip to content
AgileLogics
5 min read

Design Patterns in C#

Prerequisites: Dependency injection

The same patterns covered for Java reappear in idiomatic C#:

// Singleton — thread-safe via Lazy<T>
class AppConfig {
    private static readonly Lazy<AppConfig> _instance = new(() => new AppConfig());
    public static AppConfig Instance => _instance.Value;
    private AppConfig() {}
}

// Factory
static Shape CreateShape(string kind) => kind switch {
    "circle" => new Circle(1.0),
    "square" => new Square(1.0),
    _ => throw new ArgumentException($"Unknown shape: {kind}"),
};

Strategy is exactly what passing a Func<T>/Comparison<T> to a method already does (seen in Delegates & Events and LINQ) — C#'s first-class functions make the classic Strategy pattern's interface-plus-implementations version less often necessary than in older, pre-Java-8-style OOP code.