Reputation: 504
namespace contest
{
class Program
{
static void Main(string[] args)
{
B b = new B();
}
}
class A {
public A() {
k();
}
private void k() {
Console.WriteLine(base.GetType().Name);
}
}
class B : A {
}
}
Can someone tell me why it outputs "B" instead of "Object", doesn't base.GetType() get A's parent object therefore the root Object?
Thanks a lot
Upvotes: 0
Views: 160
Reputation: 40818
GetType
is defined on System.Object
and is not virtual. It provides the runtime type of the object from the metadata. Therefore, it doesn't matter where you call it (in a constructor or virtual method) or if you use base
or this
you are always calling the same method. You will always get the runtime type, except in the case of Nullable types where you will get the underlying type. My guess is that this is due the special boxing behavior of nullables. See this on identifying nullable types.
Upvotes: 0
Reputation: 4730
B implements/inherits from A, when you initialise B b = new B() it will just use guts of a and therefore return type of the B. Try using A b = new B(); this should return A. You need to override method and also define A as abstract.
Upvotes: 0
Reputation: 254916
That happens because
base.GetType()
means "call the GetType()
method of parent class", though you haven't overriden it. Thus base.GetType()
as well as this.GetType()
would always return class B
Upvotes: 3