What are the situations and their associated benefits of using Generics over Inheritance and vice-versa, and how should they be best combined?
Thanks for the answer
Use generics to specify an algorithm or type's behaviour which can be expressed in terms of some "unknown type" while keeping an API which is strongly typed in terms of that unknown type. The unknown type is known as a type parameter and is expressed in the code like this:
public class List
{
public void Add(T item)
}
(etc) - here T
is the type parameter. Generic methods are similar:
public void Foo(T item)
The calling code specifies the type argument it wants to work with, e.g.
List list = new List();
list.Add("hi");
Use inheritance to specialize the behaviour of a type.
I can't really think of many places where they're alternatives to each other...