A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegate types are delegate, Action and Func.
Multicast Delegate
All C# delegates have multicast capability, this means a single delegate instance can reference more than one target method. You can add or remove target methods using operators += or -=. Target methods are called in the order they were added to the delegate instance.
Create the delegate
1
delegatevoidNumbersDelegate(int a, int b);
Create methods the delegate will call, the need to have the same return type and parameters signature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassFoo { publicvoidAddNumbers(int a, int b) { Console.WriteLine("AddNumbers: " + (a + b)) } publicvoidMultiplyNumbers(int a, int b) { Console.WriteLine("MultiplyNumbers: " + (a * b)) } publicvoidSubtractNumbers(int a, int b) { Console.WriteLine("SubtractNumbers: " + (a - b)) } }
Use the delegate with one method AddNumbers
1 2 3 4 5 6 7
var foo = new Foo();
// Delegate with initial target `AddNumbers` NumbersDelegate numbersDelegate = foo.AddNumbers;
// Invoke delegate, this will call `AddNumbers` numbersDelegate(5, 5);
Multicast the delegate to have more than one target
privatevoidCount(EventRecord record) { // count logic that does something with `record` // my app didnt actually do anything with `record` but there is a SO link below for an example that did, the principle is pretty much the same though. }
privatevoidAppend(EventRecord record) { // append logic that does something with `record` }
Create a method that accepts the delegate as a parameter
Action is a void delegate, it performs a side effect and returns nothing. Func is a delegate that returns a value, the last type parameter is always the return type.
1 2 3 4 5
// Action: write to DB, caller needs nothing back Action<long, string> logEvent = (id, message) => db.Insert(id, message);
// Func: fetch from DB, caller needs the result Func<long, string> getLabel = (id) => db.QuerySingle<string>(id);
Use Action when the operation is fire-and-forget (writes, notifications, logging). Use Func when the caller needs a value to continue (queries, lookups, calculations).