Hiding a member function does not work

I think I have a miss concept. I am trying to override the behavior of a class in a subclass by replacing a public function. In the program below, I expect "B" to be written to the console, but the program will print "A". Where am I thinking wrong? And how can I achieve this. (In my real case, I cannot change class A).

    class Program
    {
        class A { public void F() { Console.WriteLine("A"); } }
        class B : A { public new void F() { Console.WriteLine("B"); } }

        static void Main(string[] args)
        {
            A x;
            x = new B();
            x.F();
            Console.ReadLine();
        }
    }
+4
source share
1 answer

The desired behavior can be obtained using the method virtualand its subsequent redefinition; pay attention to the keyword override.

class Program
{
    class A { public virtual void F() { Console.WriteLine("A"); } }
    class B : A { public override void F() { Console.WriteLine("B"); } }

    static void Main(string[] args)
    {
        A x;
        x = new B();
        x.F();
        Console.ReadLine();
    }
}

Java, , Java, # .

+3

Source: https://habr.com/ru/post/1609114/


All Articles