Synopsis: | Don't hide inherited members with the new keyword |
Language: | C# |
Severity Level: | 4 |
Category: | Object oriented |
Description: |
Not only does the
public class Book { public virtual void Print() { Console.WriteLine("Printing Book"); } } public class PocketBook : Book { public new void Print() { Console.WriteLine("Printing PocketBook"); } } This will cause behavior that you would not normally expect from class hierarchies: PocketBook pocketBook = new PocketBook(); pocketBook.Print(); // Will output "Printing PocketBook " ((Book)pocketBook).Print(); // Will output "Printing Book" It should not make a difference whether you call Print through a reference to the base class or through the derived class. So the correct version would be:
public class Book { public virtual void Print() { Console.WriteLine("Printing Book"); } } public class PocketBook : Book { public override void Print() { Console.WriteLine("Printing PocketBook"); } } |
Literature References: |
Aviva AV1010 |