Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a base class and a contitioned generic

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?

like image 991
Gerard Avatar asked Jan 30 '14 08:01

Gerard


People also ask

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.

What is the difference between a generic class and a generic method?

A generic class or structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures. A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its procedure code.

What is generic in asp net?

A generic type definition is a class, structure, or interface declaration that functions as a template, with placeholders for the types that it can contain or use. For example, the System. Collections.


1 Answers

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.
like image 91
Alexei Levenkov Avatar answered Oct 11 '22 09:10

Alexei Levenkov