Search code examples
c#.netoopgenerics.net-2.0

Ensure all elements in List<T> types are T


I want to verify that all the List<T>'s elements types are T.

I can have a List<object> containing object, string, int, Product, Supplier etc', but in my case, if the List<T> was defined as List<object> all the elements must be objects.

That is, I want to ensure that the type of the elements is the exact type of the passed in generic type, not anything else in the inheritance chain.

Example:

public void Foo<T>(List<T> list)
{
    // if not all elements are of type T (not SubClass of T) throw exception

    //...    
}

What is the best way?


Solution

  • Assuming if T is a base class you want to disallow derived classes.

    if(list.Any(element => element.GetType() != typeof(T))
        throw new ArgumentException();