0

In this example it uses polymorphysm via virtual, override keywords

 abstract class A
    {
        public virtual string Print() { return "A"; }
    }
    
    class B : A
    {
        public override string Print() { return "B"; }
    }
    
    class C : B
    {
        public virtual new string Print() { return "C"; }
    }
    
    class D : C
    {
        public override string Print() { return "D"; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            A a = new D();
    
            Console.WriteLine(a.Print());
        }
    }

Console prints B. Why B, not D? Thank you for answers

Andrii
  • 689
  • 1
  • 6
  • 12
  • 1
    `Console.WriteLine((a as D).Print())` – vasily.sib Dec 16 '20 at 08:01
  • Whoever think it's a good question consider it's reposted typical [quiz question](https://codegalaxy.io/courses/csharp/questions/c2cbcce9d7d444ed9eccb1952331ed74/public-abstract-class-a-public-virtual-string-print-return-a-public-class-b-a-pu), without any research attempt. – Sinatr Dec 16 '20 at 08:13

2 Answers2

1

Simple, because the last time you override the Print function of class A is during the declaration of class B

    class B : A
    {
        public override string Print() { return "B"; }
    }

By declaring public virtual new, you are hiding the underlying implementation of Print. So during the D declaration you are overriding the new implementation, declared at class C

Now A, has no knowledge whatsoever of what you've done, once you've hidden the function on B

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
1

That's the problem with methods that hide methods of their parent classes. It is not polymorphic. Since the variable is of type A the resolution of method Print() only knows about A.Print() and B.Print(). C.Print() and D.Print() are not overrides of A.Print(), because of the declation of C.Print() with new.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103