Reputation: 626
is there an attribute
or pattern
to tell the compiler don't allow override overridable method?
For example:
Vehicle
public class Vehicle
{
public virtual void Start() { }
}
Car
public class Car : Vehicle
{
// ################
[DontAllowOverrideAgain] //I need something like this attribute
// ################
public override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}
CoupeCar
public class CoupeCar : Car
{
// throw and error or show a message to developer
public override void Start() { }
public override void CarStart() { }
}
Upvotes: 2
Views: 546
Reputation: 3907
Here you have it, use sealed
Ref. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed
public class Car : Vehicle
{
sealed protected override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}
Upvotes: 1
Reputation: 12806
Sure, just create the first override as sealed
, which would lead to a compile time failure that the developer can see
public class Car : Vehicle
{
public sealed override void Start()
{
// Todo => codes that every car must invoke before start ...
CarStart();
// Todo => codes that every car must invoke after start ...
}
public virtual void CarStart() { }
}
Upvotes: 5