views:

550

answers:

5

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

+36  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.

Kilhoffer
+2  A: 

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

nsr81
+5  A: 

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.

Mark Bessey
I disagree. Inheritance is often misused., and most classes aren't coded with inheritance in mind. So, unless a class was designed to be inherited, it should be sealed by default. Then, when someone inherits off of your sealed class, it might force them to think about it a little more.
Robert Paulson
I agree with Robert (i.e. I disagree with Mark). Inheritance is something which takes a great deal of careful consideration. For example, any time you call one virtual method from another, you are locking that implementation - changing the call to be the other way round can break derived classes.
Jon Skeet
It also **slightly** helps with performance.
MagicKat
Maybe I've been in the "framework" business for too long, but as far as I'm concerned, any class that's not designed for re-use and subclassing isn't done yet. I'm not convinced that putting "sealed" on every class is going to accomplish much in terms of making people think.
Mark Bessey
Actually the opposite will be correct, use "sealed" always and if needed remove it. See this thread http://stackoverflow.com/questions/123773/is-oop-completely-avoiding-implementation-inheritance-possible#124591
OscarRyz
There are a lot of ways to "reuse" a class besides sub-classing.
Jonathan Allen
A: 

The sealed keyword would work, but still you can derive from the class using reflection IIRC.

dalle
you can also access private members with reflection. doesnt mean its a good idea
Kilhoffer
I highly doubt that you can derive from the class using reflection, either. If someone shows me a class deriving from System.String, I'll believe it - but until then...
Jon Skeet
Inherit via reflection? I don't even see how that would work or that the CLR would pay any attention even if you tried. Can you expand on that claim?
Robert Paulson
No kidding. Explain that one. How is that possible?
Kilhoffer
A: 

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

Max Schmeling