Say I have an abstract parent class called “Parent” that implements a method called “DisplayTitle”. I want this method to be the same for each subclass that inherits “Parent” – I would like a compile error if a subclass attempts to implement their own “DisplayTitle” method. How can I accomplish this in C#. I believe in Java, I’d just mark the method as “final”, but I can’t seem to find an alternative in C#. I’ve been messing around with “sealed” and “override”, but I can’t get the behavior that I’m looking for.
For example, in this code:
using System;
namespace ConsoleApplication1
{
class Parent
{
public void DisplayTitle() { Console.WriteLine("Parent's Title"); }
}
class ChildSubclass : Parent
{
public void DisplayTitle() { Console.WriteLine("Child's Own Implementation of Title");
}
static void Main(string[] args)
{
ChildSubclass myChild = new ChildSubclass();
myChild.DisplayTitle();
Console.ReadLine();
}
}
}
I’d like to receive a compile error saying that the “ChildSubClass” can’t override “DisplayTitle”. I currently get a warning – but it seems like this is something that I should be able to do and I don’t know the proper attributes to label the method.
The rough equivalent is
sealedin C#, but you normally only need it for virtual methods – and yourDisplayTitlemethod isn’t virtual.It’s important to note that
ChildSubclassisn’t overridingDisplayTitle– it’s hiding it. Any code which only uses references toParentwon’t end up calling that implementation.Note that with the code as-is, you should get a compile-time warning advising you to add the
newmodifier to the method inChildSubclass:You can’t stop derived classes from hiding existing methods, other than by sealing the class itself to prevent the creation of a derived class entirely… but callers which don’t use the derived type directly won’t care.
What’s your real concern here? Accidental misuse, or deliberate problems?
EDIT: Note that the warning for your sample code would be something like:
I suggest you turn warnings into errors, and then it’s harder to ignore them 🙂