Well, “the essential idea” of “delegation” is simply: “identify Someone Else that you can ask.”
In this example, the Compare
class exists to “compare two objects.” But you’ve said that it is to delegate that responsibility to some other function that is not a part of its own definition. Furthermore, you specify exactly what an acceptable “delegate function” must look like.
The Delegate Function
declaration specifies what that delegate must look like. “An acceptable delegate must return a Boolean
, and it must accept (exactly …) two Integer
parameters.” The language ensures, at compile-time, that this is so.
In your two, separate, calls to the CheckCompare
method of the Compare
class, you provide separate references to two functions, GreaterThan
and LessThan
, both of which are conformant to the strictures set out in the Delegate Function
declaration. Therefore, the language permits them to be used in the calls. And, as instructed, the CheckCompare
method invokes the delegate-function that it has been given, when told to do so.
It does not know (but, it does not care) exactly which delegate it is. The language ensures that “an acceptable delegate” has been provided, and all this method needs to do, is to call “it.”
solved Delegates vs Calling of Functions [closed]