Category Archives: delegates

Extensibility through Delegates

One of the key tenets of the SOLID principles used in object oriented design is the Open/Closed Principle. This states that software entities should be open for extension but closed for modification. This rather cryptic statement means that objects shouldn’t have to be changed every time requirements change. Clearly this is not always possible but objects can be made more tolerant to change through OO techniques such as inheritance and polymorphism. This is typically implemented using interfaces or abstract base classes that push responsibility out to concrete classes. Here is an excellent example.

However, this isn’t the only means to achieve this. C# is a rich language which provides multiple, complementary mechanisms to solve similar problems. Through delegates and lambdas, an alternative approach can be used. The following example demonstrates how a class can be extended without modification by allowing the caller to supply their own implementation.

internal class Helper
{
    internal static string UpdateString(string value)
    {
        return value.ToUpper();
    }
        
    internal static string UpdateString(Func<string> f)
    {
        return f();
    }
          
}

String s = "Hello";
Console.WriteLine(Helper.UpdateString(s));
Console.WriteLine(Helper.UpdateString(() => s.ToLower()));

Output

HELLO
hello

This simple example demonstrates how the Helper class can be offer an extensibility point via a method overload that accepts a delegate (in this case a Func<string>). The caller is able to override the default implementation which converts the string to upper case by providing its own implementation, in the form of a lambda expression.

For more on lambdas and delegates see my previous post on Linq.