ערוך

שתף באמצעות


sealed (C# Reference)

When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.

class A {}
sealed class B : A {}

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.

Example

In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.

class X
{
    protected virtual void F() { Console.WriteLine("X.F"); }
    protected virtual void F2() { Console.WriteLine("X.F2"); }
}

class Y : X
{
    sealed protected override void F() { Console.WriteLine("Y.F"); }
    protected override void F2() { Console.WriteLine("Y.F2"); }
}

class Z : Y
{
    // Attempting to override F causes compiler error CS0239.
    // protected override void F() { Console.WriteLine("Z.F"); }

    // Overriding F2 is allowed.
    protected override void F2() { Console.WriteLine("Z.F2"); }
}

When you define new methods or properties in a class, you can prevent deriving classes from overriding them by not declaring them as virtual.

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.

When applied to a method or property, the sealed modifier must always be used with override.

Because structs are implicitly sealed, they cannot be inherited.

For more information, see Inheritance.

For more examples, see Abstract and Sealed Classes and Class Members.

sealed class SealedClass
{
    public int x;
    public int y;
}

class SealedTest2
{
    static void Main()
    {
        var sc = new SealedClass();
        sc.x = 110;
        sc.y = 150;
        Console.WriteLine($"x = {sc.x}, y = {sc.y}");
    }
}
// Output: x = 110, y = 150

In the previous example, you might try to inherit from the sealed class by using the following statement:

class MyDerivedC: SealedClass {} // Error

The result is an error message:

'MyDerivedC': cannot derive from sealed type 'SealedClass'

Remarks

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.

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also