Click here to Skip to main content
15,883,809 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I Working on console application I ask why result is
ClassB
IT must be ClassC
i executed app on console and it give me ClassB
why final result ClassB i expect it will be ClassC

What I have tried:

C#
using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
    
 namespace apptest
 {
     class Program
     {
         static void Main(string[] args)
         {
             classA a = new classC();
             Console.WriteLine(a.Print());
             Console.ReadKey();
         }
         public class classA
         {
             public virtual string Print()
             {
                 return "ClassA";
             }
    
         }
         public class classB: classA
         {
             public override string Print()
             {
                 return "ClassB";
             }
    
         }
         public class classC: classB
         {
             public new string Print()
             {
                 return "ClassC";
             }
         }
     }
 }
Posted
Updated 16-Oct-21 1:51am

Few things, you have defined the variable as classA. You create the object from ClassC but still the signatures are from ClassA because of the definition.

So when you call the Print method it is executed from classB because it overrides the the method thus having the same signature. Even though ClassC also defines a Print method, it's not the same method because of the new keyword, instead, it's a different method. For more information have a look at
- new modifier - C# Reference | Microsoft Docs[^]
- Knowing When to Use Override and New Keywords - C# Programming Guide | Microsoft Docs[^]
 
Share this answer
 
It's because a is a ClassA variable: it only "knows" about ClassA and overrides in derived classes.
In ClassB, the Print method is overridden, so when you try to call Print on a it searches for the highest level override it can find - but since ClassC doesn't override it in favour of hiding the existing implementations, it can't find it - it's not in the override inheritance chanin any more.

So it calls the ClassB.Print, and you get the result you see.

To check it, try this:
C#
classC c = new classC();
classA a = c;
Console.WriteLine(a.Print());
Console.WriteLine(c.Print());
This explains it pretty well: Knowing When to Use Override and New Keywords - C# Programming Guide | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900