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?
The generic class works with multiple data types. A normal class works with only one kind of data type.
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.
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.
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()
:
repeatGeneric
and repeatGenericVar
will be IEnumerable<Cat>
(note that var
statically finds the type, shown to highlight the fact type is known statically)repeat
and repeatVar
will be IEnumrable<Animal>
despite the fact that Cat
was passed in.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With