Create a hierarchy of classes A, B and C so that the code below compiles and displays the text "ABC"

static void Main(string[] args) { var b = new B(); var c = new C(); ((A)c).PrintMessage(); ((A)b).PrintMessage(); c.PrintMessage(); } 

Tell me how to build inheritance correctly, but I’m constantly catching

System.InvalidCastException

  • Add work, even if they are not working :) - Alex Tremasov

2 answers 2

https://ideone.com/cUNAkG

 class A { public virtual void PrintMessage() { Console.Write("A"); } } class B : A { public sealed override void PrintMessage() { Console.Write("B"); } } class C : A { public new void PrintMessage() { Console.Write("C"); } } 
  • and why sealed? - Grundy
  • @Grundy, overdid it. At first I had C:B , but then I realized that I was nosyachil. And sealed stayed. - Qwertiy 5:41 pm
 class B : A { ... } class C : A { ... } 

In the declarations of the PrintMessage methods in classes A , B and C you will need to use the keywords virtual , override and new respectively.