0 like 0 dislike
36 views
asked in C sharp (C#) by (4.7k points)
recategorized by

In programming language 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.

is object of class

Your answer

pre, code

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

0 like 0 dislike
answered by (4.7k points)
edited by

Use typeof and GetType() method so:

typeof(SpecifiedClass) == obj.GetType()
if (Obj.GetType() == typeof(ClassName))

Examples

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

Related questions

0 like 0 dislike
1 answer 5 views
0 like 0 dislike
1 answer 5 views
0 like 0 dislike
1 answer 12 views
0 like 0 dislike
1 answer 24 views
0 like 0 dislike
1 answer 8 views
0 like 0 dislike
1 answer 18 views
0 like 0 dislike
1 answer 5 views
0 like 0 dislike
1 answer 12 views
0 like 0 dislike
1 answer 8 views
0 like 0 dislike
1 answer 12 views
...