How to know if class instance inherits another class?

Asked

Viewed 293 times

6

I’m using reflection to know if one class inherits another, what I found was this:

bool herda = typeof(A).IsAssignableFrom(typeof(B));

But I want to do it in the variable getting your type.

Here’s the following definition I need:

public class A { }

public class B : A { }

public class Principal
{               
    public static void Main(string[] args)
    {
        B b = new B();
        // quero saber se classe B herda classe A através da variável b
    }
}
  • 2
  • 2

    A tip: almost always do not need this, this information you have without asking for the code. It has several features that people use because they don’t understand what the code really needs, these resources exist for quite rare cases, it may be yours, but statistically it is more likely that it is not.

3 answers

10


Since you want to check the "parent" type from an instance variable of the "child" type, you can use the operator is.

If you want to use the method IsSubclassOf, will need to make use of the method GetType.

using System;

public class Program
{
    public static void Main()
    {
        B b = new B();
        Console.Write(b is A); // True
        Console.Write(b.GetType().IsSubclassOf(typeof(A))); // True
    }
}

public class A { }

public class B : A { }

See working on . NET Fiddle

  • It is recommended to use is for this?

  • 2

    @Park Sure, that’s what he’s for.

  • According to ECMA-335 the operator is is much more efficient than the methods Type.IsSubclassOf(Type) and Type.IsAssignableFrom(Type) because it generates a single instruction isinst while the methods of reflection generate a StackFrame the allocation of this StackFrame in theStackTrace(memory allocation and stacking) and the method call itself .

1

Do the following:

typeof(B).IsSubclassOf(typeof(A))

See working on Coding Ground

  • I cannot place the instance variable inside the typeof()

  • 1

    I adjusted the answer, try now

1

You can catch your kind with GetType() and use IsSubclassOf

b.GetType().IsSubclassOf(typeof(A));

Type.Issubclassof(Type) Method

Determines whether the current type derives from the specified type.

Functioning in dotnetFiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.