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.