Reputation: 1566
Is there a way to require a property to be overridden in a derived class when base class is not abstract? For example:
public abstract class BaseClass
{
protected abstract string Test {get;}
}
internal class FirstClass : BaseClass
{
protected override string Test => "First Class";
// Methods common to FirstClass and SecondClass
}
internal class SecondClass : FirstClass
{
protected override string Test => "Second Class"
}
Is there a way to force property test
in FirstClass
to be overridden if any class inherits from FirstClass
?
There is practical need for this (maybe not a big one) is that while logging information, we want to log source of error (class name etc.), therefore we want to force all leaf derived class to override certain properties.
Upvotes: 0
Views: 442
Reputation: 659956
Is there a way to require a property to be overridden in a derived class when base class is not abstract?
(The original question asks about fields. Fields may not be overridden at all; you meant "property", not "field".)
No.
Whether a derived class chooses to override or not is an implementation detail that is up to the author of that derived class, who knows more about the business domain of that class than the author of the base class knows.
The only way to make a member that must be overridden is to make it abstract.
It is legal to override with an abstract. This would be legal, for instance:
abstract class BaseClass
{
protected virtual string Test => "Base";
}
abstract class FirstClass : BaseClass
{
// override abstract is slightly unusual but legal
protected override abstract string Test { get; }
// Concrete derived classes must override
}
class SecondClass : FirstClass
{
protected override string Test => "Second Class"
}
Upvotes: 8