Please consider the following design:
public interface IBook
{
string Author { get; set; }
string Title { get; set; }
}
abstract class BaseBook : IBook
{
private string _title;
public virtual string Author
{
get
{
Console.WriteLine("Base book GET!");
return _title;
}
set
{
Console.WriteLine("Base book SET!");
_title = value;
}
}
public string Title { get; set; }
}
class Book : BaseBook
{
}
class SuperBook : Book
{
public override string Author
{
get
{
Console.WriteLine("SuperBook GET!");
return base.Author;
}
set
{
Console.WriteLine("SuperBook SET!");
base.Author = value;
}
}
public string Title { get; set; }
}
Is there any way make the Title
property of the BaseBook
base class sealed to prevent the property from being overridden in derived classes (such as the Book
and the SuperBook
classes)?
If you compile your program, you will receive the following warning:
This means that your
SuperBook.Title
is hiding the Title from BaseBook. Hiding is different from overriding, because the member is not virtual. What happens with hiding is this: if the compiler is treating your object as an instance of the SuperBook class, it will call theSuperBook.Title
method. If, however, the compiler treats your instance as a BaseBook class, the call will be made toBaseBook.Title
.For instance:
If you make the property virtual, then the result is that the most derived implementation will always be called, because the compiler uses an virtual table to find which method to call.
Finally, if you want the property to be virtual so that every call gets resolved to
SuperBook.Title
, but don't want the user to override it on more derived classes, all you have to do mark the propertysealed override
.Use "sealed" keyword on your Title property.
You won't be able to override the
Title
property unless it is markedvirtual
anyway. What you cannot prevent it from is being hidden by somebody using thenew
operator.If it's not virtual, then it cannot be overriden, it can only be hid (using the
new
keyword). Unlike Java, C# methods (and and by extension properties) are not implicitly virtual, but rather explicitly.You already cannot override BaseBook.Title. SuperBook.Title actually hides BaseBook.Title rather than overrides it. It should really have the new keyword on it if hiding was intended; in fact you'll get a compiler warning to that effect.