Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forbid a class method/property to be overridden in C#?

I believe I want a some methods and properties of a class to be unoverridable and use the base's implementation in all derived classes. How to achieve this? sealed keyword doesn't seem to work and says "method can not be sealed because it is not an override".

like image 903
Ivan Avatar asked Jul 05 '11 16:07

Ivan


Video Answer


1 Answers

Members are sealed by default in C# - unless they're marked as virtual, they can't be overridden in derived classes anyway.

They can be shadowed in derived classes, admittedly:

public new void SomeMethod()
{
}

... but that's not the same as overriding. There's no way you can prevent this, but if a caller uses a compile-time type of the base class, they won't end up calling this accidentally anyway.

If you could give us more details of exactly what you're trying to prevent (from both the caller's POV and the code being called) we may be able to help more.

like image 185
Jon Skeet Avatar answered Oct 05 '22 20:10

Jon Skeet