Alex Rivera | Logout

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

Asked 2011-07-05T16:24:15.847
10

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".

Edit
Report

1 Answer

0

This is precisely what sealed keyword is for.

http://msdn.microsoft.com/en-us/library/ms173150.aspx

A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.

If you've overridden a method from base class than use sealed. If you've declared a method in the class and don't want it to be overridden in any derived classes than don't mark it as virtual. Only virtual members can be overridden.

answered 2011-07-05T16:27:52.873

Your Answer