Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if an object is from a class but not superclass?

Tags:

c#

object

class

In C# how can you find if an object is an instance of certain class but not any of that class’s superclasses?

“is” will return true even if the object is actually from a superclass.

like image 413
Ali Avatar asked Nov 30 '22 12:11

Ali


2 Answers

typeof(SpecifiedClass) == obj.GetType()
like image 174
Chaowlert Chaisrichalermpol Avatar answered Dec 06 '22 15:12

Chaowlert Chaisrichalermpol


You could compare the type of your object to the Type of the class that you are looking for:

class A { }
class B : A { }

A a = new A();
if(a.GetType() == typeof(A)) // returns true
{
}

A b = new B();
if(b.GetType() == typeof(A)) // returns false
{
}
like image 25
Andy Avatar answered Dec 06 '22 15:12

Andy