Difference between a base class and a contitioned generic

c#, generics, polymorphism

Solution

I think most visible difference is type of the parameter inside method will be different - in generic case actual type, non-generic - always `BaseClass`.

This information is useful when you need to call other generic classes/methods.

 class Cat : Animal {}

 void DoSomething<T>(T animal) where T:Animal
 {
    IEnumerable<T> repeatGeneric = Enumerable.Repeat(animal, 3);
    var repeatGenericVar = Enumerable.Repeat(animal, 3);
 } 
 void DoSomething(Animal animal)
 {
    IEnumerable<Animal> repeat = Enumerable.Repeat(animal, 3);
    var repeatVar = Enumerable.Repeat(animal, 3);
 } 

Now if you call both with `new Cat()`:

- type of both `repeatGeneric` and `repeatGenericVar` will be `IEnumerable<Cat>` (note that `var` statically finds the type, shown to highlight the fact type is known statically)

- type of both `repeat` and `repeatVar` will be `IEnumrable<Animal>` despite the fact that `Cat` was passed in.

Problem

I noticed after some time using generics that there was not much difference between this: ``` public void DoSomething<T>(T t) where T : BaseClass{ } ``` and this: ``` public void DoSomething(BaseClass t){ } ``` The only difference I have seen so far is that the first method could be added other constraints, like interfaces or `new ()`, but if you use it just the way that I wrote it, I don´t see much difference. Can anybody point any important factors about choosing one or another?

Original source