-5

Why does Console show type B not A, even though a2 was assigned to new B()? I cannot understand exactly what happens in A a2 = new B().

class A { }
class B : A { }

...

A a1 = new A();
A a2 = new B();

Console.WriteLine(a2.GetType());
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42

4 Answers4

3

A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of polymorphism in C#.

w.b
  • 11,026
  • 5
  • 30
  • 49
1

Because you have created instance of class B not A and you are able to hold in variable of type A due to inheritance feature of OOP as you are inheriting your B class from A.

But the actual type of the a2 is B not A though it can be represent as A as well, but the GetType() reutrns the run-time type which is B.

You can have a look at this SO post too which explains what the GetType is expected to return for an object and what is typeof() and how we can use is for inheritance hierarchy checking.

Hope it helps.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Just because you refer to it through type A doesn't mean that the actual type suddenly changes to A, it's still a B object. You decided to create one with new B().

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.

Stilgar
  • 22,354
  • 14
  • 64
  • 101