12. Generics and Delegates
Generics let you write code that works with any type while staying type-safe and fast, with no casting. The type is a parameter written in angle brackets: List<int>, Dictionary<string, int>, or your own Box<T>. You can make generic classes, structs, interfaces, methods and delegates. Constraints (where T : class, struct, new(), SomeBase, IComparable<T>) tell the compiler what a type argument must support, so you can call its members. The compiler usually infers the type argument from the arguments of a generic method.
A delegate is a type that references a method, so a method can be passed around like a value. Func<> (returns a value; the last type is the result), Action<> (returns nothing) and Predicate<T> (returns bool) are built-in delegates that cover almost every need. Lambda expressions (x => x * 2) are short inline methods that can capture variables from the surrounding code (closures). Delegates can be combined: += adds another method (a multicast delegate) and -= removes it.
Events build on delegates to implement the publisher/subscriber pattern: a class exposes an event, other code subscribes with +=, and the class raises it when something happens (a button click, a finished download). Passing delegates into methods (higher-order functions) is the idea behind LINQ: Where, Select and OrderBy all take lambdas.
Key points to remember
- Generic naming: T for a single type, TKey / TValue for several, or a descriptive TEntity.
- default(T) gives the default value of any T (0 for numbers, null for reference types).
- Without constraints you can only use members of object. Add where T : IComparable<T> to compare values, where T : new() to create instances, where T : class or struct to restrict kind.
- Func<int, string, bool> takes an int and a string and returns bool. Action<int> takes an int and returns nothing.
- Lambdas capture variables, not copies: the lambda sees later changes to a captured variable.
- Call a delegate safely with action?.Invoke(...), which does nothing if no method is attached.
- Events can only be raised from inside the class that declares them, and outside code can only use += and -=. This protects the publisher.
- Unsubscribe (-=) from events of long-lived objects, otherwise the subscriber cannot be garbage-collected.
- Prefer the built-in EventHandler<TEventArgs> for events and Func / Action over declaring your own delegate types.
Example 1: Generic class
var b = new Box<int> { Value = 5 };
var s = new Box<string> { Value = "hi" };
Console.WriteLine(b.Value + " " + s.Value);
class Box<T>
{
public T Value { get; set; }
}
Show output
Output5 hi
Example 2: Generic methods and constraints
static T Max<T>(T a, T b) where T : IComparable<T>
=> a.CompareTo(b) >= 0 ? a : b;
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
Console.WriteLine(Max(3, 7));
Console.WriteLine(Max("apple", "pear"));
Console.WriteLine(Max(2.5, 1.5));
string x = "first", y = "second";
Swap(ref x, ref y);
Console.WriteLine(x + " " + y);
Show output
Output7 pear 2.5 second first
Example 3: A generic collection class
var stack = new MyStack<string>();
stack.Push("a");
stack.Push("b");
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Count);
try { stack.Pop(); stack.Pop(); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
class MyStack<T>
{
private readonly List<T> _items = new();
public int Count => _items.Count;
public void Push(T item) => _items.Add(item);
public T Pop()
{
if (_items.Count == 0) throw new InvalidOperationException("Stack is empty");
T item = _items[^1];
_items.RemoveAt(_items.Count - 1);
return item;
}
}
Show output
Outputb 1 Stack is empty
Example 4: Two type parameters and new() constraint
var pair = new Pair<string, int>("age", 30);
Console.WriteLine(pair);
var created = Factory.Create<List<int>>(); // needs new()
created.Add(1);
Console.WriteLine(created.Count);
class Pair<TKey, TValue>
{
public TKey Key { get; }
public TValue Value { get; }
public Pair(TKey key, TValue value) { Key = key; Value = value; }
public override string ToString() => $"{Key} = {Value}";
}
static class Factory
{
public static T Create<T>() where T : new() => new T();
}
Show output
Outputage = 30 1
Example 5: Delegates and multicast
Operation op = Add;
Console.WriteLine(op(2, 3));
op = Multiply;
Console.WriteLine(op(2, 3));
Action greet = () => Console.Write("Hello ");
greet += () => Console.WriteLine("World"); // multicast: both run
greet();
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
delegate int Operation(int a, int b);
Show output
Output5 6 Hello World
Example 6: Func, Action, Predicate and lambdas
Func<int, int> square = x => x * x;
Func<int, int, int> add = (a, b) => a + b;
Action<string> say = m => Console.WriteLine(m);
Predicate<int> isEven = n => n % 2 == 0;
say("Square of 4 is " + square(4));
Console.WriteLine(add(2, 3));
Console.WriteLine(isEven(4));
Func<string> hello = () =>
{
string name = "Ana";
return "Hi " + name; // statement lambda
};
Console.WriteLine(hello());
Show output
OutputSquare of 4 is 16 5 True Hi Ana
Example 7: Closures and functions that return functions
static Func<int, int> Multiplier(int factor) => x => x * factor; var triple = Multiplier(3); Console.WriteLine(triple(5)); int counter = 0; Action increment = () => counter++; // captures the variable increment(); increment(); increment(); Console.WriteLine(counter);
Show output
Output15 3
Example 8: Passing a delegate to a method
static List<int> Filter(List<int> source, Func<int, bool> rule)
{
var result = new List<int>();
foreach (int n in source)
if (rule(n)) result.Add(n);
return result;
}
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
Console.WriteLine(string.Join(",", Filter(numbers, n => n % 2 == 0)));
Console.WriteLine(string.Join(",", Filter(numbers, n => n > 4)));
Console.WriteLine(string.Join(",", numbers.Where(n => n < 3))); // LINQ does the same
Show output
Output2,4,6 5,6 1,2
Example 9: Events
var button = new Button();
button.Clicked += (sender, label) => Console.WriteLine("Handler 1: " + label);
button.Clicked += (sender, label) => Console.WriteLine("Handler 2");
button.Click("OK");
class Button
{
public event EventHandler<string>? Clicked;
public void Click(string label)
{
Clicked?.Invoke(this, label); // raise the event if anyone listens
}
}
Show output
OutputHandler 1: OK Handler 2
Example 10: Event with custom data (EventArgs)
var sensor = new Thermometer();
sensor.TooHot += (s, e) => Console.WriteLine($"Warning: {e.Temperature} degrees");
sensor.Set(25);
sensor.Set(41);
class TemperatureEventArgs : EventArgs
{
public int Temperature { get; }
public TemperatureEventArgs(int t) { Temperature = t; }
}
class Thermometer
{
public event EventHandler<TemperatureEventArgs>? TooHot;
public void Set(int value)
{
if (value > 35) TooHot?.Invoke(this, new TemperatureEventArgs(value));
}
}
Show output
OutputWarning: 41 degrees