TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C# Coding Standard
Search

Rule:  7@404Checked automatically with code checker

Synopsis:Don't hide inherited members with the new keyword
Language:C#
Severity Level:4
Category:Object oriented


Description:

Not only does the new keyword break Polymorphism, one of the most essential object-orientation principles, it also makes subclasses more difficult to understand. Consider the following two classes:

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