Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealed keyword in association with override

Is it always necessary to follow the sealed keyword with override in the signature of a method like the below code:

public sealed override string Method1(){.....} 

I mean, if I want to "seal" the method within the base class without overriding, is the override keyword still necessary?

like image 840
Victor Mukherjee Avatar asked Dec 13 '12 10:12

Victor Mukherjee


People also ask

Can you override a sealed class?

You can't inherit from a sealed class, so no inheritance, no override. The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. When applied to a class, the sealed modifier prevents other classes from inheriting from it.

What is sealed override?

Sealing a method only makes sense if you override it. What happens here is the following: You are overriding a method from a base class ( override ) and tell the compiler that classes derived from your class are no longer allowed to override this method ( sealed ).

Can we override sealed method in C#?

A method can also be sealed, and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class.

What is sealed override C#?

sealed (C# Reference) You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.


1 Answers

Sealing a method only makes sense if you override it.

What happens here is the following:
You are overriding a method from a base class (override) and tell the compiler that classes derived from your class are no longer allowed to override this method (sealed).

If the method is a new one declared by you in your class and you want to prevent derived classes from overriding it, simply don't declare it as virtual.

If the method is declared in a base class but is not overridable sealing it wouldn't make any sense, because it already can't be overriden.

like image 82
Daniel Hilgarth Avatar answered Sep 25 '22 14:09

Daniel Hilgarth