Cheat Sheet: Delegates, Lambdas & Closures in Delegate Arrays C#
What is a Delegate?
A delegate is a type that represents references to methods with a specific signature. It allows methods to be passed as parameters.
C# Basic Delegate Example
using System;
delegate int MathOperation(int x, int y);
class Program
{
static int Add(int x, int y) => x + y;
static void Main()
{
MathOperation op = Add; // Assign method to delegate
Console.WriteLine(op(3, 5)); // Output: 8
}
}
Why use Delegates?
- Allows passing functions as parameters.
- Enables flexible function execution.
- Forms the basis for events and callbacks.
Delegate Arrays vs. Method Chaining (+=
)
Delegates in C# and VB.NET allow multiple methods to be stored or combined, but they work differently.
C# Example: Delegate Array (No Automatic Chaining)
delegate void FooDelegate();
class Program
{
static void Method1() => Console.WriteLine("Method1 called");
static void Method2() => Console.WriteLine("Method2 called");
static void Main()
{
FooDelegate[] fooArray = { Method1, Method2 };
fooArray[0](); // Calls only Method1
fooArray[1](); // Calls only Method2
}
}
C# Example: Method Chaining (+=
)
delegate void FooDelegate();
class Program
{
static void Method1() => Console.WriteLine("Method1 called");
static void Method2() => Console.WriteLine("Method2 called");
static void Main()
{
FooDelegate foo = Method1;
foo += Method2; // Chaining methods
foo(); // Calls both Method1 and Method2
}
}
Key Differences:
Feature | Delegate Array { f1, f2 } |
Method Chaining (+= ) |
---|---|---|
Separate Invocations | Yes, each function is independent | ❌ No, all methods execute together |
Single Delegate Execution | Yes, one method per call | ❌ No, all chained methods execute |
Can Remove Methods (-= ) |
❌ No | Yes |
Iteration Required to Call All | Yes (foreach ) |
❌ No |
When to Use?
Use Case | Delegate Array { f1, f2 } |
Method Chaining (+= ) |
---|---|---|
Executing a list of independent functions | Yes | ❌ No |
Combining methods into a single call | ❌ No | Yes |
Dynamically adding/removing methods at runtime | ❌ No | Yes (+= , -= ) |
Storing Lambdas in a Delegate Array
C# Example
using System;
delegate int MathOperation(int x, int y);
class Program
{
static void Main()
{
MathOperation[] operations = new MathOperation[]
{
(x, y) => x + y, // Addition
(x, y) => x - y, // Subtraction
(x, y) => x * y // Multiplication
};
Console.WriteLine(operations[0](3, 5)); // 8 (Addition)
Console.WriteLine(operations[1](3, 5)); // -2 (Subtraction)
Console.WriteLine(operations[2](3, 5)); // 15 (Multiplication)
}
}
Why?
- Store multiple functions dynamically.
- Execute different behaviors without if/else chains.
Using a Delegate Array with Closures
C# Example
using System;
delegate int CounterFunction();
class Program
{
static void Main()
{
CounterFunction[] counters = new CounterFunction[]
{
MakeCounter(10),
MakeCounter(100),
MakeCounter(1000)
};
Console.WriteLine(counters[0]()); // 11
Console.WriteLine(counters[1]()); // 101
Console.WriteLine(counters[2]()); // 1001
}
static CounterFunction MakeCounter(int start)
{
int count = start;
return () => ++count; // Closure captures `count`
}
}
Why?
- Each closure remembers its own state.
- Different instances operate independently.
Looping Over Delegate Arrays Dynamically
C# Example
foreach (var operation in operations)
{
Console.WriteLine(operation(6, 2));
}
Why?
- Applies multiple operations to the same data.
- Removes the need for hardcoded function calls.
🚀 Summary
Feature | C# | VB.NET |
---|---|---|
Basic Delegate Assignment | Yes | Yes |
Method Chaining (+= ) in Delegates |
Yes | Yes |
Store lambdas in a delegate array | Yes | Yes |
Store closures in a delegate array | Yes | Yes |
Loop through the array dynamically | Yes | Yes |
Independent function instances in an array | Yes | Yes |
👉 Verdict: Delegates, lambdas, and closures work great in arrays! They allow for dynamic function storage, flexible execution, and independent function instances. 🚀