Delegates
A delegate is a reference type, like the other reference types you’ve seen in this book, but instead of referring to an object, a delegate refers to a method. This is called encapsulating the method. When you create the delegate, you specify a method signature and return type; you can encapsulate any matching method with that delegate.
You create a delegate with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it, as in the following:
public delegate int FindResult(object obj1, object obj2);
This declaration defines a delegate named FindResult, which will encapsulate any method that takes two objects as parameters and that returns an int.
Once the delegate is defined, you can encapsulate a member method with that delegate by creating an instance of the delegate, passing in a method that matches the return type and signature. Notice that the delegate has no method body; that’s because you’re not defining the method here. You’re simply saying that this delegate can encapsulate any method with the appropriate signature; you don’t care what it does or how it does it, as long as it has the right parameters and returns the correct type.
As an alternative, you can use anonymous methods or lambda expressions, as described later in this chapter. In either case, you can use the delegate to invoke that encapsulated method.
Delegates decouple the class that declares the delegate from the class that uses the delegate. That’s part of ...
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