Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override method of sealed class?

In WinRT (C#, XAML), ScrollViewer is a sealed class, and I can't extend it, but I need to overwrite some methods (for example: ScrollToHorizontalOffset).

Is it possible to override methods of a sealed class?

like image 764
jimpanzer Avatar asked Jun 12 '14 13:06

jimpanzer


People also ask

Can sealed method be overridden?

If you create a sealed method, it cannot be overridden.

Can we inherit methods of sealed classes?

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.

What methods are impossible to override?

Methods that are declared private or static cannot be overridden either because they are implicitly final. It is also impossible for a class that is declared final to become a super class.

Can we override sealed method in C#?

A sealed method in an unsealed class is a method which cannot be overridden in a derived class of this class.


2 Answers

No - in order to override a method, you have to derive from it, which you can't do when the class is sealed.

Basically, you need to revisit your design to avoid this requirement...

like image 97
Jon Skeet Avatar answered Oct 29 '22 02:10

Jon Skeet


You can't inherit from a sealed class, so no inheritance, no override.

See: override C#

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

See: sealed C#

When applied to a class, the sealed modifier prevents other classes from inheriting from it.

like image 7
Habib Avatar answered Oct 29 '22 03:10

Habib