How to do it in C #. I believe in Java, I would just mark the method as "final", but I cannot find an alternative in C #.
The rough equivalent is sealed in C #, but you usually only need a virtual method, and your DisplayTitle method DisplayTitle not virtual.
It is important to note that ChildSubclass does not override the DisplayTitle - it hides it. Any code that uses references only to Parent will not invoke this implementation.
Note that with as-is code, you should get a compilation warning that recommends adding the new modifier to the method in ChildSubclass :
public new void DisplayTitle() { ... }
You cannot stop derived classes from hiding existing methods, except to seal the class itself to prevent the creation of the entire derived class ... but there will be no callers who do not use the derived type directly.
What is your real problem here? Accidental abuse or intentional problems?
EDIT: Note that the warning for your sample code will look something like this:
Test.cs(12,19): warning CS0108: 'ConsoleApplication1.ChildSubclass.DisplayTitle()' hides inherited member 'ConsoleApplication1.Parent.DisplayTitle()'. Use the new keyword if hiding was intended.
I suggest you turn warnings into errors, and then it's harder to ignore them :)
source share