-1

Can someone please help with some code to check if an object inherits from a specific type.

Here is my code:

public class Class1
{

}

public class Class2 : Class1
{

}

private void TestType()
{
    var collection = new List<Class1>();
    collection.Add(new Class1());
    collection.Add(new Class2());

    var results = new List<Class1>();

    foreach (var item in collection)
    {
        if (item.GetType().IsAssignableFrom(typeof(Class1)))
        {
            results.Add(item);
        }
    }
}

In the above code, the results collection only has the Class1 object, and not both of the objects.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • 1
    [IsAssignableFrom](https://msdn.microsoft.com/en-us/library/system.type.isassignablefrom%28v=vs.110%29.aspx) contains a lot of explanations/samples... Have you read it carefully? – Alexei Levenkov Jun 14 '16 at 01:43

1 Answers1

0

You can do this:

public class Class1
{

}

public class Class2 : Class1
{

}

private void TestType()
{
    var collection = new List<Class1>();
    collection.Add(new Class1());
    collection.Add(new Class2());

    var results = new List<Class1>();

    foreach (var item in collection)
    {
        Class1 c1 = (item as Class1);   // Won't throw if not Class1
        if ( c1 != null )
        {
            results.Add(c1);
        }
    }
}
Darrin Cullop
  • 1,170
  • 8
  • 14