What is the meaning of base class restriction?

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 only accept type arguments Productor infer from it.

Here I used methods to illustrate the question, but the same thing applies to classes.

+4
source share
2 answers

The first method allows you to do things such as typeof(T)that you could not do with a non-generic type, since the object itself may be null (since you need to call item.GetType()).

You can also dictate the return type (if instead it was not invalid), for example:

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 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());

, ( ).

+4

, - item, Product.

, , T. T PremiumProduct, item List<PremiumProduct>, , Product .

+2

Source: https://habr.com/ru/post/1663042/


All Articles