Search code examples
c#inheritanceinterfacepartial-classesoverriding

Enforce override method to base class


I have the following code:

public partial class Root : ICustomInterface
{
    public virtual void Display()
    {
        Console.WriteLine("Root");
        Console.ReadLine();
    }
}
public class Child : Root
{
    public override void Display()
    {
        Console.WriteLine("Child");
        Console.ReadLine();
    }
}
class Program
{
    static void Main(string[] args)
    {
        Root temp;
        temp = new Root();
        temp.Display();
    }
}

Output: "Root"
Desired output: "Child"

When I instantiate a Root object and call the Display() method I want to display the overridden method in Child is this possible.

I need this because I must create a plugin that's an extension to the base code and voids the Display() method of the Root class and implements only the plugin's method Child


Solution

  • No it's not possible you have to instantiate a Child object instead of a root

    Root temp;
    temp = new Child();
    temp.Display();
    

    if you don't want to modify temp then you have to modify Root display method to print "child" instead of root