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
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
.