Correct way to see if the current instance of a superclass is a subclass from within the superclass

Say I have a class called SuperClass and a class called SubClass. SubClass extends from SuperClass. Inside the definition of SuperClass I have a method that intends to check if this class is an instance of SubClass.

if (this.GetType() == typeof(SubClass))
    log.Info("This SuperClass is a SubClass");
else
    log.Info("This SuperClass is NOT a SubClass");

This works, but I'm always very skeptical when something works correctly (especially on the first try). I wanted to make sure this was the best way (safest, most readable, correct) to do what I want.

Jon Skeet
people
quotationmark

I think you're just looking for the is operator:

if (this is SubClass)

In particular, that will also continue if this is an instance of a subclass of SubClass.

If you then want to use this as SubClass, e.g. to get at a member declared in SubClass, you should consider the as operator too:

SubClass sub = this as SubClass;
if (sub != null)
{
    // Use sub here
}

If you want to detect that this is an instance of exactly SubClass (and not further derived types) then the check you've got is already the right one.

One word of warning: the need to check for types at execution time is often a bit of a design smell. Think about whether there are alternative ways of achieving whatever your goal is. Sometimes there are (e.g. by introducing a new virtual or abstract member in the base class) and sometimes there aren't... but it's always worth thinking about.

people

See more on this question at Stackoverflow