Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing override of individual methods in C#

I know that I can use the sealed in order to prevent other classes to inherit a certain class, but is it possible to allow inheritance but prevent overriding of some virtual methods?

like image 552
leeza Avatar asked Mar 11 '11 15:03

leeza


People also ask

How do you prevent a method from being overridden in C#?

To prevent being overridden, use the sealed in C#. When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.

Which two declarations prevent the overriding of a method?

Remember, though syntactically you can use private, static and final modifier to prevent method overriding, but you should always use final modifier to prevent overriding. final is best way to say a method is complete and can't be overridden.

Which modifier is used to prevent method overriding in C#?

3. Which of the given modifiers can be used to prevent Method overriding? Explanation: When an instance method declaration includes the sealed modifier, the method is said to be sealed method. It means a derived class cannot override this method.


2 Answers

Only virtual methods can be overridden.
Just leave out virtual, and your method will not be overridable.

like image 152
SLaks Avatar answered Sep 24 '22 13:09

SLaks


you can also use sealed modifier to prevent a derived class from further overriding the method.

check this out: Sealed methods

like image 33
scatman Avatar answered Sep 23 '22 13:09

scatman