C#
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

VulpesRank #55 · 29.2K reputationPosted Oct 4, 2014, 2:28 AM EDT
However, this only works because 'base' here - as previously discussed - is really an instance of B. If it were an instance of A you'd get a NullReferenceException because System.Object doesn't have a base class.
There is a way to always get 'Object' without using typeof(A):
The output is:
Object
Object
However, we're having to use reflection to do this and so the code is relatively slow to execute.
VulpesRank #55 · 29.2K reputationPosted Oct 2, 2014, 5:11 AM EDT
The 'base' keyword doesn't alter the type of the current instance - it merely enables you to access base class members through that instance which might otherwise be hidden.
So, in this case, the current instance is of type B (even though its accessing code in its base class A) and so that's what base.GetType().Name returns.
If you changed your Main method to this:
you'd find that the second line printed out A because that's now the runtime type of the current instance.
VulpesRank #55 · 29.2K reputationPosted Oct 3, 2014, 1:22 AM EDT
Max Power4 reputationPosted Oct 2, 2014, 7:46 PM EDT
Max Albish125 reputationPosted Oct 3, 2014, 6:20 PM EDT
Max Albish125 reputationPosted Oct 4, 2014, 5:07 AM EDT
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts