How to check if a class is of a certain type, ignoring inheritance?

Viewed 249

Lets say I have a parent class and a child class like this:

public class Parent{}
public class Child : Parent{}

Now in some method I want to find classes that are of type Parent, but I'm not interested in classes of type Child. So lets say I do something like this:

var listOfParents = new List<Parent>();

foreach(item in someListOfItems)
{
   if(item is Parent)
   {
      listOfParents.Add(item);
   }

} 

This would give me all classes of type Parent, but also all classes of type Child, since it implements Parent. How could I go about only retrieving the classes of type Parent while ignoring all subclasses? I also want to avoid doing lots of if checks like if (item is Parent && !(item is Child) since this could get messy if there's lots of classes implementing Parent.

2 Answers

Use GetType:

if(item.GetType() == typeof(Parent))

Note that this will throw NullReferenceException for when item is null unlike type checking with is.

Adding to GuruStron answer. This might remove also the null case.

if(item?.GetType() == typeof(Parent))
Related