Sealed Classes and Methods

Sealed Classes and Methods in C#C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can’t inherit from that class. In the case of a method, this means that you can’t override that method.

sealed class mClass
{
  // etc.




class DerivedClass : mClass // wrong. Will give compilation error.

{
   // etc.










Inheritance


The most likely situation when you’ll mark a class or method as sealed will be if the class or method is internal to the operation of the library, class, or other classes that you are writing, so you are sure that any attempt to override some of its functionality will cause problems. You might also mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending your classes in a manner that is contrary to the licensing agreements. In general, however, you should be careful about marking a class or member as sealed, since by doing so you are severely restricting how it can be used. Even if you don’t think it would be useful to inherit from a class or override a particular member of it, it’s still possible that at some point in the future someone will encounter a situation you hadn’t anticipated in which it is useful to do so. The .NET base class library frequently uses sealed classes in order to make these classes inaccessible to third-party developers who might want to derive their own
classes from them. For example, string is a sealed class.

Declaring a method as sealed serves a similar purpose as for a class, although you rarely will want to declare a method as sealed.

class mClass
{
  public sealed override void mMethod()
  {
      // etc.
   }
 }


class DerivedClass : mClass
{
 public override void mMethod()//wrong. Will give compilation error
   {
   }






















It does not make sense to use the sealed keyword on a method unless that method is itself an override of another method in some base class. If you are defining a new method and you don’t want anyone else to override it, then you would not declare it as virtual in the first place. If, however, you have overridden a base class method then the sealed keyword provides a way of ensuring that the override you supply to a method is a “final” override in the sense that no one else can override it again. 

No comments:

Post a Comment