Search code examples
c#overridingvirtualradix

Explanation needed: virtual, override and base


Why doesn't the ", Second ID: " string in O.W2() get printed out? I know that the D2 property is empty.

using System;

public class O
{
    public string F { get; set; }
    public string L { get; set; }
    public string D { get; set; }

    public virtual string W()
    {
        return this.W2();
    }

    public virtual string W2()
    {
        return string.Format("First Name : {0}, Last name: {1}, ID: {2}", F, L, D);
    }
}

public class S : O
{
    public string D2 { get; set; }

    public override string W()
    {
        return base.W2();
    }

    public override string W2()
    {
        return base.W2() + string.Format(", Second ID: {0}", this.D2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        O o = new S();

        o.D = "12345678";
        o.F = "John";
        o.L = "Jones";

        Console.WriteLine(o.W());

        // Output: First Name : John, Last name: Jones, ID: 12345678
    }
}

Solution

  • Because you called override W() which in turn calls base.W2(). Inside the class, base.W2() is determined statically (at compile time) to be the one in the base class:

    public override string W()
    {
        // directly calls W2() from the base class, ignores the override
        return base.W2(); 
    }
    

    If you want polymorphism for this scenario, you should omit base and just call W2():

    public override string W()
    {
        // goes to the override
        return W2(); 
    }