Chapter 4. Advanced C#
In this chapter, we cover advanced C# topics that build on concepts explored in previous chapters. You should read the first four sections sequentially; you can read the remaining sections in any order.
Delegates
A delegate dynamically wires up a method caller to its target method. There are two aspects to a delegate: type and instance. A delegate type defines a protocol to which the caller and target will conform, comprising a list of parameter types and a return type. A delegate instance is an object that refers to one (or more) target methods conforming to that protocol.
A delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method.
A delegate type declaration is preceded by the keyword delegate, but otherwise it resembles an
(abstract) method declaration. For example:
delegate int Transformer (int x);
To create a delegate instance, you can assign a method to a delegate variable:
class Test
{
static void Main()
{
Transformer t = Square; // Create delegate instance
int result = t(3); // Invoke delegate
Console.WriteLine (result); // 9
}
static int Square (int x) { return x * x; }
}Note
Technically, we are specifying a method
group when we refer to Square without brackets or arguments. If the
method is overloaded, C# will pick the correct overload based on the
signature of the delegate to which it’s being assigned.
Invoking ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access