Search code examples
c#.netvirtual

Virtual and New in C#


I have the following classes in C#:

public class BaseClass
{
    public virtual void DoSomethingVirtual()
    {
        Console.WriteLine("Base.DoSomethingVirtual");
    }

    public new void DoSomethingNonVirtual()
    {
        Console.WriteLine("Base.DoSomethingNonVirtual");
    }
}

public class DerivedClass : BaseClass
{
    public override void DoSomethingVirtual()
    {
        Console.WriteLine("Derived.DoSomethingVirtual");
    }

    public new void DoSomethingNonVirtual()
    {
        Console.WriteLine("Derived.DoSomethingNonVirtual");
    }
}

class ConsoleInheritanceTrial
{
    static void Main(string[] args)
    {
        Console.WriteLine("Derived via Base Reference.");

        BaseClass BaseRef = new DerivedClass();
        BaseRef.DoSomethingVirtual();
        BaseRef.DoSomethingNonVirtual();

        Console.WriteLine();
        Console.WriteLine("Derived via Dereived Reference.");

        DerivedClass DerivedRef = new DerivedClass();
        DerivedRef.DoSomethingVirtual();
        DerivedRef.DoSomethingNonVirtual();

        Console.Read();
    }
}

After running Main function, I got this:

Derived Via Base Reference
Derived.DoSomethingVirtual
Base.DoSomethingNonVirtual

Derived Via Derived Reference
Derived.DoSomethingVirtual
Derived.DoSomethingNonVirtual

Why did the baseRef.DoSoemthingNonVirtual call the base function? Has it got something to do with the "new" keyword in the Derived Class for that function? I understand the importance of "virtual" and "overrides". My confusion was caused by the statement: BaseClass BaseRef = new DerivedClass();


Solution

  • Why did the BaseRef.DoSoemthingNonVirtual call the base function?

    This is your declaration:

    BaseClass BaseRef = new DerivedClass();
    

    Here you create an object of type DerivedClass and you assign a reference of it to a variable that is of type BaseClass. This can be done since, the DerivedClass has as a base type the BaseClass.

    Then here

    BaseRef.DoSomethingNonVirtual
    

    you call the method DoSomethingNonVirtual.

    What is the type of BaseRef?

    It is BaseClass. So the method of this class is called and not the method of DerivedClass.

    So the problem here is that you have created an object of type DerivedClass and you assigned the reference of this object to a variable of type BaseClass. So the CLR, when see this call for the first time

    BaseRef.DoSomethingNonVirtual
    

    has to resolve the type of BaseRef, then look the object's method table, pick the corresponding IL and at the last produce the corresponding native code. How CLR would resolve this? As an object of type BaseClass and not DerivedClass.