Could someone please explain when would I want to use delegation instead of inheritance?
Delegation is an alternative to inheritance for reusing code among multiple classes. Inheritance uses the IS-A relationship for re-use; delegation uses the HAS-A reference relationship to do the same. Inheritance and delegation have the same kind of relationship that, say, Aspirin and Tylenol, have.
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance.
No. According to the C# documentation, delegate types are sealed, and you cannot create a new delegate type that inherits from an existing one.
Delegation is a technique that promotes code reuse by allowing runtime function invocation in the context of a specific instance – regardless of the hierarchical lineage of instance and function.
When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.
One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.
They have nothing to do with each other. Delegation is a behavior. Inheritance is a model technique.
Inheritance is for modeling "is-a". A computer "is-a" electronic system.
Delegation is how methods provide results. Sometimes one object will delegate work to another object. Delegation can be via any relationship -- you can delegate to a superclass, to a member of a composite or aggregate, or any relationship.
If 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