Search code examples
c#gethashcode

Why is the type of 'base' object my concrete type?


It seems a very simple question, but clearly I'm missing something. I did a test:

class A
{
    public override int GetHashCode()
    {
        Console.WriteLine(base.GetType().Name);
        return 0;
    }
}

I was expecting to find 'object' but I find 'A'. I was relying on this behaviour to invoke the base GetHashCode is particular cases withing an implementation, calling base.GetHashCode() and I was expecting the object implementation to be invoked.

What's wrong?


Solution

  • base. notation changes method that is called for overridden virtual methods (like GetHashCode in your sample - base.GetHashCode() calls object.GetHashCode, this.GetHashCode() calls A.GetHashCode()). base. can also be used to hidden base class' method, but it is not the case in this sample.

    Since GetType is not virtual and there is no hiding then calling this.GetType() and base.GetType() behaves identical and calls object.GetType which returns "The exact runtime type of the current instance" as specified in documentation