tags:

views:

188

answers:

4

Assuming I have the superclass A, and the subclasses A1 and A2 which inherit from A, how could I get the subclass type of the variables in the code below?

A _a1 = new A1();
A _a2 = new A2();
// Need type of A1 and A2 given the variables _a1 and _a2.

Also, if I had another subclass A2_1 which is a sublcass of A2, how do I get the lowest subclass type given code below?

A _a2_1 = new A2_1();

EDIT: Thanks for answers. What a boo boo. Over thinking the problem and didn't even try GetType(). =/

+2  A: 

Console.WriteLine(_a1.GetType());

GetType can return the run-time type of the variable irrespective of declaration type.

shahkalpesh
+1  A: 

For the first - just use _a1.GetType() and _a2.GetType(). On the 2nd - what do you mean by "lowest subclass type"; or: what answer do you expect... (which might help us understand what you mean...)

Marc Gravell
+2  A: 

You could use the GetType() method:

Type type = _a1.GetType();
Type subtype = _a2_1.GetType();
Jose Basilio
+1  A: 

GetType() on any object always gives you the real object type, never the type of a superclass. If you are creating instances of subclasses using "new subclass()", then "subclass" is the Type of the object.

Calling GetType() is all you need for your situations.

womp