0

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?

Bruno Peres
  • 15,845
  • 5
  • 53
  • 89

3 Answers3

2

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?

oRole
  • 1,316
  • 1
  • 8
  • 24
  • 1
    @RufusL `is` is recommended. It makes for more readable code, it handles the case where `object2` is `null`, and in C#7 you can write `if (object2 is List foo) { Console.WriteLine(foo.Count); }`. – 15ee8f99-57ff-4f92-890c-b56153 Oct 02 '17 at 17:44
  • 1
    @RufusL oRole just reminded me, `is` is true if it's a subclass, equivalent to `Type.IsAssignableFrom()` -- so if you want to check *exact* type equality, excluding subclasses, comparing `GetType() == ` is the only choice in that case. – 15ee8f99-57ff-4f92-890c-b56153 Oct 02 '17 at 17:52
1

what about?

  Type myListElementType = object2.GetType().GetGenericArguments().Single();
  if (myListElementType  == typeof(Test))
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

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);
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140