Bruno Peres
Bruno Peres

Reputation: 16365

Check if instance is a collection of given type

Let's say I have this dummy code:

var object1 = new Test();

So, if I need check if object1 is an instance of Test class I can do:

var type = typeof(Test);
Console.WriteLine(object1.GetType() == type); // will print true

But now I have this object2 (A list of Test objects):

var object2 = new List<Test>
{
    new Test(),
    new Test(),
    new Test()
};

My question is: How can I check if object2 is a list of Test instances?

Upvotes: 0

Views: 85

Answers (3)

oRole
oRole

Reputation: 1346

You could either use .GetType() to afterwards compare it to the typeof(List<Test>) ..

if (object2.GetType() == typeof(List<Test>))
{
    // do something
}

.. or you could use the is expression like:

if (object2 is List<Test>)
{
    // do something
}

These if-statements will be true if object2 is a List of Test-objects.

Note
Both fit for what you want to do but there are also some differences between .GetType(), typeof(..) and is. These are explained here: Type Checking: typeof, GetType, or is?

Upvotes: 2

Metro Smurf
Metro Smurf

Reputation: 38335

There is a more generic method of finding the type bound to the list by reflecting over the interfaces implemented on the underlying IList. This is an extension method I use for finding the bound type:

/// <summary>
/// Gets the underlying type bound to an IList. For example, if the list
/// is List{string}, the result will be typeof(string).
/// </summary>
public static Type GetBoundType( this IList list )
{
    Type type = list.GetType();

    Type boundType = type.GetInterfaces()
        .Where( x => x.IsGenericType )
        .Where( x => x.GetGenericTypeDefinition() == typeof(IList<>) )
        .Select( x => x.GetGenericArguments().First() )
        .FirstOrDefault();

    return boundType;
}

In the O.P.'s case:

bool isBound = object2.GetBoundType() == typeof(Test);

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

what about?

  Type myListElementType = object2.GetType().GetGenericArguments().Single();
  if (myListElementType  == typeof(Test))

Upvotes: 1

Related Questions