Reputation: 7760
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(). =/
Upvotes: 2
Views: 2812
Reputation: 116977
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.
Upvotes: 1
Reputation: 51468
You could use the GetType() method:
Type type = _a1.GetType();
Type subtype = _a2_1.GetType();
Upvotes: 2
Reputation: 1062745
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...)
Upvotes: 1
Reputation: 33476
Console.WriteLine(_a1.GetType());
GetType can return the run-time type of the variable irrespective of declaration type.
Upvotes: 5