Delegates and Events
A delegate type describes a method signature — delegate int Operation(int a, int b) matches any method taking two ints and returning an int. A variable of that delegate type can hold a reference to any matching method, and calling the variable calls whichever method it currently points to.
using System;
class Program {
delegate int Operation(int a, int b);
static int Add(int a, int b) { return a + b; }
static int Subtract(int a, int b) { return a - b; }
static void Main() {
Operation op = Add;
Console.WriteLine(op(5, 3));
op = Subtract;
Console.WriteLine(op(5, 3));
}
}8 2
Events
event wraps a delegate with publish/subscribe semantics: outside code can += a handler onto it, but can only invoke it from inside the declaring class. ?.Invoke() safely calls the event only if at least one handler has subscribed.
using System;
class Publisher {
public event Action<string> OnMessage;
public void Raise(string msg) {
OnMessage?.Invoke(msg);
}
}
class Program {
static void Main() {
var pub = new Publisher();
pub.OnMessage += (msg) => Console.WriteLine("Received: " + msg);
pub.Raise("hello");
}
}Received: hello
Next: nullable types and null safety — representing 'no value' for a value type, and the operators C# gives you to handle it concisely.
Practice exercise
Define a delegate Operation matching int(int, int), and a method Add(int, int). Declare an Operation variable set to Add, call it with (5, 3), and print the result.