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();