1010.md

February 3, 2022 ยท View on GitHub

Compiler warning CS0114 is issued when breaking Polymorphism, one of the most essential object-orientation principles. The warning goes away when you add the new keyword, but it keeps sub-classes 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(); // Outputs "Printing PocketBook "

((Book)pocketBook).Print(); // Outputs "Printing Book"

It should not make a difference whether you call Print() through a reference to the base class or through the derived class.