Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it Appropriate to use Generics Versus Inheritance?

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

I'm going to try to state the motivation for this question as best I can: I have a class as shown below:

class InformationReturn<T> where T : Info
{
    InformationReturn(Employee employee, List<T>) { ... }
}

Now suppose I have a repository that takes an InformationReturn argument, that has to strore different fields in a DB depending on the type of Info object T is. Is it better to create different repositories each for the type T is; one repository that uses reflection to determine the type; or is there a better way using inheritance capabilities over/with generics?

Note: other client code must operate differently based on the type of T as well.

like image 407
Laz Avatar asked Apr 28 '09 18:04

Laz


2 Answers

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.

like image 137
C. Ross Avatar answered Sep 16 '22 22:09

C. Ross


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.

like image 42
Andrew Hare Avatar answered Sep 17 '22 22:09

Andrew Hare