When is it Appropriate to use Generics Versus Inheritance?
You should use generics when you want only the same functionality applied to various types (Add, Remove, Count) and it will be implemented the same way. Inheritance is when you need the same functionality (GetResponse) but want it to be implemented different ways.
Generics and inheritance are two separate things. Inheritance is an OOP concept and generics are a CLR feature that allows you specify type parameters at compile-time for types that expose them.
Inheritance and generics actually work quite well together.
Inheritance:
Inheritance allows me to create one type:
class Pen { }
and then later create another type that extends Pen
:
class FountainPen : Pen { }
This is helpful because I can reuse all the state and behavior of the base class and expose any new behavior or state in FountainPen
. Inheritance allows me to rapidly create a more specific version of an existing type.
Generics:
Generics are a CLR feature that let me create a type like this:
class Foo<T>
{
public T Bar { get; set; }
}
Now when I use Foo<T>
I can specify what the type of T
will be by providing a generic type argument:
Foo<int> foo = new Foo<int>();
Now, since I have specified that T
shall be an int
for the object I have just created, the type of Foo.Bar
will also be int
since it was declared of type T
.