Reputation: 1407
What is the difference between these two methods?
public void Add<T>(T item) where T : Product
public void Add(Product item)
From what I understand, both will accept only arguments that are of type Product
or derive from it.
Here I've used methods to exemplify the question, but the same goes to classes.
Upvotes: 4
Views: 122
Reputation: 27377
The first method lets you do things such as typeof(T)
, which you couldn't do with the non-generic type, since the object itself may be null (since you'd need to invoke item.GetType()
).
You're also able to dictate the return type (if instead it was not void), like so:
public class Butter : Product { }
public class Egg : Product { }
public class Product { }
public T AddGeneric<T>(T item) where T : Product
{
//Do something
return item;
}
public Product Add(Product item)
{
//Do something
return item;
}
//Even though we know it's going to return an Egg, we still need to cast here
//If we want to treat t as an Egg, rather than as a Product
Product t = Add(new Egg());
//No cast needed
Egg tt = AddGeneric(new Egg());
Also note that a generic method will create one method per type at compile time (and at run time when invoking via reflection).
Upvotes: 4
Reputation: 113392
Both are alike in that they can do anything to item
that can be done on a Product
.
The former though can also do things with a type related to the type of T
. If T
was type PremiumProduct
then it could add item
to a List<PremiumProduct>
while the other cannot because being a Product
does not suffice for that.
Upvotes: 2