When this code runs the output is "Child running" even though I am casting it to the Parent class? Im probably doing it wrong, if so, how can i achieve the desired result of having an output of "Parent running"? The Parent instance = new Child(); has to remain like that.
class Program
{
class Parent
{
public virtual void Run()
{
Console.WriteLine("Parent running.");
}
}
class Child : Parent
{
public override void Run()
{
Console.WriteLine("Child running.");
}
}
static void Main(string[] args)
{
Parent instance = new Child();
(instance as Parent).Run();
Console.ReadLine();
}
}
EDIT:
Noticed if I remove the virtual keyword from the Parent class and mark the Child's version of this method as new it "solves" the issue.
class Program
{
class Parent
{
public void Run()
{
Console.WriteLine("Parent running.");
}
}
class Child : Parent
{
public new void Run()
{
Console.WriteLine("Child running.");
}
}
static void Main(string[] args)
{
Parent instance = new Child();
(instance as Parent).Run();
Console.ReadLine();
}
}