Search code examples
c#polymorphismoverridingnew-operatorvirtual-inheritance

understanding override and new property


    class Car
    {
        public virtual string Name { get; set; }

        public virtual void CheckName()
        {
            throw new NotImplementedException();
        }

    }

class ConveribleCar : Car
{
    public override string Name { get; set; }

    public override  void CheckName()
    {
        Console.WriteLine("this :{0} , base : {1}", this.Name, base.Name); 
    }

}

class Minivan : Car
{
    public new string Name { get; set; }

    public override void CheckName()
    {
        Console.WriteLine("this :{0} , base : {1}", this.Name, base.Name);
    }
}


and the calling code : 
Car car = new Minivan(){Name = "Minivan"};//using new property
Car car2 = new ConveribleCar(){Name = "Convertible"};//using override property
car.CheckName(); //prints this : Minivan, base : (null or empty)
car2.CheckName(); //prints this : Convertible , base :(null or empty)

I understand the theory of virtualization in methods , if you use the keyword new it hiddes the methods in the derived class, if you use override the new implementation is taken in count and its the one that is used, but I do not understand why this is not happening with properties , I should expect according to my understanding that the base.Name in car should print "Minivan" (becasue is hidding the derived Name in class Minivan) ans this.Name will be null. (as fas as I know)

Also when I inspect the object car in VS car.Name is null even though it prints "Minivan" , this behavior seems really strange to me. Can anyone give me an explanation of whats going on in the sample code , or Can anyone suggest a better example of how to really see new and override properties working in a proper way so that I can understand, maybe my example is very bad.

Thanks in advance.


Solution

  • No matter you override or hide the Name property, there will be 2 separate properties with that name, and you can access both implementations in the subclass by this.Name and base.Name.

    To see your expected behaviour, you should probably directly print out car.Name, you'll see nothing comes out - it is null. car is of compile time type Car, so the subclass implementation is not used. It resolves to Car.Name, which is not set. Note that printing car2.Name prints the overridden property, precisely because that property is overridden.

    So why printing car.Name gives you null, while printing this.Name in CheckName doesn't work?

    CheckName is overridden so the implementation in Minivan will be called. Now in the context of the method, this is of compile time type Minivan, isn't it? So in that context, this.Name refers to the subclass implementation of Name, hence Minivan is printed.