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

StackOverflow https://stackoverflow.com/questions/23569554

  •  19-07-2023
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

This will work but you've coupled your super and sub classes where the super really shouldn't know about the sub. Create a virtual method on the super class that the sub will override to do the actual work. You can call this method from inside or outside of the super class to do the work you need. If the work needs to be done on members of the super class, then make them protected so the sub class can access them.

Let me add that almost anytime you need to check the type of an object, you aren't doing object oriented programming correctly and there is a better design to be found. Usually it's the sub class that needs to be doing the work that the type checking class is trying to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top