Thursday 3 May 2018

What is a delegate?

Purpose:
  • This is another really simple question that one would expect any developer to answer in a split second but amazingly many stumble. This is usually because they have a weak understanding of language mechanisms and simply code to recipes that they have learned. Or they stumble through code and trial-an-error their way through their coding life.

Potential Answer:
The most common answer is that it is a function pointer. Surprising function pointers actually refers to C and C++ concepts so an answer like this perhaps points to a rehearsed or canned answer. A better answer is that it is a special type that defines a method signature and a instance of that delegate type can be assigned to any method with a compatible signature. Put another way a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.

What would be a good sign is if the developer can tie the question to real world examples. Like using delegates to pass methods as parameters.

Or perhaps talking about Action and Func and Predicates as language features that make delegate use easier. For the sake of completeness:
  • Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
  • Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
  • Predicate is a special kind of Func often used for comparisons takes generic parameters and returns bool.

No comments:

Post a Comment