How can I keep a class from being inherited in C#?
-
03-07-2019 - |
Question
In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?
Solution
You're looking for the sealed
keyword. It does exactly what the final
keyword in Java does. Attempts to inherit will result in a compilation error.
OTHER TIPS
Also be aware that "I don't think anybody will ever need to inherit from this" is not a good reason to use "sealed". Unless you've got a specific need to ensure that a particular implementation is used, leave the class unsealed.
As Joel already advised, you can use sealed
instead of final
in C#.
http://en.csharp-online.net/CSharp_FAQ:_Does_CSharp_support_final_classes
The sealed
modifier will do what final
does in Java.
Also, although this probably isn't what you're looking for in this situation, marking a class as static
also keeps it from being inherited (it becomes sealed behind the scenes).
The sealed
keyword would work, but still you can derive from the class using reflection IIRC.