Sunday, September 27, 2009

sealed - A keyword in C#


When applied to a class, the “sealed” modifier prevents other classes from inheriting from this class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

using System;
sealed class MyClass
{
    int x;
    int y;
}

It is an error to use the abstract modifier with a sealed class, because an abstract class must be inherited by a class that provides an implementation of the abstract methods or properties.

You can also use the “sealed” modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration. When applied to a method or property, the sealed modifier must always be used with override.

public class D : C
{
    public sealed override void DoWork() { }
}

Structs are implicitly sealed; therefore, they cannot be inherited.

To determine whether to seal a class, method, or property, you should generally consider the following two points:
  •  The potential benefits that deriving classes might gain through the ability to customize your class.
  •  The potential that deriving classes could modify your classes in such a way that they would no longer work correctly or as expected.

No comments: