0

I am learning about virtual functions in C# and I've come across this problem I can't wrap my head around. I have the following code in C#:

namespace ConsoleApp1
{
    class A
    {
        public virtual void F()
        {
            Console.WriteLine("A.F");
        }
    }
    class B : A
    {
        public override void F()
        {
            Console.WriteLine("B.F");
        }
    }
    class C : B
    {
        public new virtual void F()
        {
            Console.WriteLine("C.F");
        }
    }
    class D : C
    {
        public override void F()
        {
            Console.WriteLine("D.F");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            D d = new D();
            A a = d;
            B b = d;
            C c = d;
            a.F();
            b.F();
            c.F();
            d.F();
            c = new C();
            c.F();
            Console.ReadLine();
        }
    }
}

Why the output is this? It doesn't make sense to me at all. Can someone explain? Output:

B.F 
B.F 
D.F 
D.F 
C.F
LearningMath
  • 851
  • 4
  • 15
  • 38
  • The `new` keyword effectively kills inheritance. There are very few use cases for it. – spender Jun 23 '17 at 02:34
  • May you please explain the logic behind the output? It's a very weird output to me. – LearningMath Jun 23 '17 at 02:38
  • Can you explain which part in particular is confusing to you? – Rob Jun 23 '17 at 02:39
  • I think https://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new explains the problem well enough to be duplicate... If it is not enough - please read it carefully and then [edit] your post with explanation why you expect code to behave differently and what part you don't understand. – Alexei Levenkov Jun 23 '17 at 02:43
  • Those examples are with just two classes. I read the post and understand it now but only for two classes. When there are multiple classes in the hierarchy I actually don't know what happens when you call F() on 'a' for example. What I know is this: If a variable 'a' is of type 'A' and holds an object of type 'D', if 'do_something' is virtual, then the implementation of 'do_something' in 'D' is called. But I can't make the analogy when there are multiple classes. Thanks. – LearningMath Jun 23 '17 at 02:49
  • 1
    Try to picture it as if C.F() and D.F() are different method from A.F() and B.F() even if they have the same signature. I think then it makes sense. – Etienne Jun 23 '17 at 04:09

0 Answers0