What are the benefits/advantages of using delegates? Can anyone provide any simple examples?
Benefits of DelegatingGives you the time and ability to focus on higher-level tasks. Gives others the ability to learn and develop new skills. Develops trust between workers and improves communication. Improves efficiency, productivity, and time management.
Advantages to using them in design:Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate [Func<T,bool>] to filter on, without having to write new code in the Where method.
1. A delegate is a type safe function pointer. That is, they hold reference(Pointer) to a function. The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as type safe function pointers.
Multicast delegates help to invoke multiple callbacks. Events encapsulate delegate and implement publisher and subscriber model.
They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.
Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:
var namesOfAdults = people.Where(person => person.Age >= 18) .Select(person => person.Name);
(That can also be represented as a query expression, but let's not stray too far from delegates.)
Another way of thinking of a delegate is as a single-method interface type. For example, the EventHandler
delegate type is a bit like:
public interface IEventHandler { void Invoke(object sender, EventArgs e) }
But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.
For more on delegates and events, see my article on the topic. Its focus is events, but it covers delegates too.
This is a pretty vague topic, but here are a few things to consider -
Delegates are basically a cleaner, easier function pointer. Any place where function pointers were used in C++, you can think delegate.
Advantages to using them in design:
[Func<T,bool>]
to filter on, without having to write new code in the Where methodPotential disadvantages:
~can~
, particularly if used naively, lead to code that is more difficult to readIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With