In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
Solution-1: Use the final keyword (from C++11) So, it'll not be inherited by any class. If you try to inherit it, the compiler will flash an error that “a final class cannot be used as a base class“. Note that you can create an object of the final class as show in the main() method here.
You can't prevent inheritance (before C++11's final keyword) - you can only prevent instantiation of inherited classes. In other words, there is no way of preventing: class A { ... }; class B : public A { ... };
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With