C Sharp Delegates and Plug-in Methods with Delegates
Learn how delegates enable plug-in style methods in C#, allowing behavior to be swapped in at runtime.
The Plug-in Method Concept
A plug-in method is a method that is passed into another method through a delegate parameter, allowing the receiving method's behavior to be customized without modifying its code.
Passing Methods as Parameters
By defining a method parameter as a delegate type, you allow callers to supply any matching method, effectively plugging in custom logic at runtime.
Real-World Use Cases
This pattern is commonly used for sorting with custom comparison logic, filtering collections, and implementing simple event-driven behavior.
Benefits of This Approach
Using delegates for plug-in methods keeps your code flexible and open to extension, since new behavior can be added without changing existing method signatures.
Building a Plug-in Method Step by Step
The classic example is a method that transforms every item in an array. The method itself knows how to loop, but the actual transformation is plugged in by the caller.
public delegate int Transformer(int x);
public static class Util
{
public static void Transform(int[] values, Transformer t)
{
for (int i = 0; i < values.Length; i++)
values[i] = t(values[i]);
}
}
class Program
{
static int Square(int x) => x * x;
static int Double(int x) => x * 2;
static void Main()
{
int[] data = { 1, 2, 3, 4 };
Util.Transform(data, Square); // 1 4 9 16
Util.Transform(data, Double); // 2 8 18 32
Util.Transform(data, x => x - 1); // lambda plugged in directly
Console.WriteLine(string.Join(" ", data));
}
}
- Declare a delegate type that describes the signature: one
intin, oneintout. - Give the general method a parameter of that delegate type.
- Call the delegate inside the method as if it were a normal method.
- At the call site, pass any method or lambda whose signature matches.
The key idea is the split of responsibility. Transform owns the looping and stays unchanged forever, while each caller decides what should happen to every item. Adding a new rule, such as cubing or clamping values, needs no edit to the utility class at all. This is the open/closed principle in a very small form: open for extension, closed for modification.
Using Func and Action Instead of Custom Types
Modern C# code rarely declares its own delegate types for simple cases. The built-in generic delegates cover most needs:
Func<T, TResult>for methods that return a value.Action<T>for methods that return nothing.Predicate<T>andComparison<T>for tests and sorting.
public static IEnumerable<T> Where<T>(IEnumerable<T> items, Func<T, bool> rule)
{
foreach (var item in items)
if (rule(item)) yield return item;
}
var bigOrders = Where(orders, o => o.Amount > 5000);
var names = new List<string> { "Ravi", "Anu", "Kiran" };
names.Sort((a, b) => a.Length.CompareTo(b.Length)); // plug in sort rule
This is exactly how LINQ works: Where, Select and OrderBy are plug-in methods that accept your logic as delegates.
A practical plug-in: pricing rules
Business code uses the same trick to swap rules without long if chains. A checkout method can accept a discount rule, and the caller chooses which one applies today.
decimal Checkout(decimal total, Func<decimal, decimal> discount) => discount(total);
Func<decimal, decimal> festive = t => t * 0.85m;
Func<decimal, decimal> flat200 = t => t > 1000 ? t - 200 : t;
Console.WriteLine(Checkout(1500m, festive)); // 1275.00
Console.WriteLine(Checkout(1500m, flat200)); // 1300
Rules can even be stored in a dictionary keyed by name and picked from configuration at runtime.
Delegates or Interfaces?
| Choose a delegate when | Choose an interface when |
|---|---|
| Only one method needs to be swapped | Several related methods belong together |
| Callers want to pass a quick lambda | The behaviour needs its own state and setup |
| Logic changes per call | Logic is registered once, for example through dependency injection |
Pitfalls to Watch
- Invoking a delegate that is
null; uset?.Invoke(x)when a plug-in is optional. - Lambdas capturing a loop variable or field and seeing a later value than expected.
- Multicast delegates with return values: only the last method's result is returned.
- Passing heavy logic as long inline lambdas; a named method is easier to test and read.