Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I keep a class from being inherited in C#?

In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?

like image 894
user18931 Avatar asked Sep 30 '08 19:09

user18931


People also ask

How do you prevent a class from inheritance?

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.

How can you prevent class from being inherited in C has?

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.

How can I set up my class so it won't be inherited from in C++?

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 { ... };


4 Answers

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.

like image 110
Kilhoffer Avatar answered Nov 20 '22 13:11

Kilhoffer


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.

like image 29
Mark Bessey Avatar answered Nov 20 '22 12:11

Mark Bessey


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

like image 22
Nasir Avatar answered Nov 20 '22 12:11

Nasir


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).

like image 40
Max Schmeling Avatar answered Nov 20 '22 11:11

Max Schmeling