Sunday, May 17, 2009

Sealed Modifier

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. In the following example, C inherits from B but C cannot override the virtual function F that is declared in A and sealed in B.

class A
{
protected virtual void F() { Console.WriteLine("A.F");}
protected virtual void F2() { Console.WriteLine("A.F2");}
}
class B : A
{
sealed protected override void F() { Console.WriteLine("B.F");}
protected override void F2() {Console.WriteLine("A.F3");}
}
class C : B
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); }

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

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 (C# Programming Guide).
Example
Copy Code
// cs_sealed_keyword.cs
using System;
sealed class SealedClass
{
public int x;
public int y;
}

class MainClass
{
static void Main()
{
SealedClass sc = new SealedClass();
sc.x = 110;
sc.y = 150;
Console.WriteLine("x = {0}, y = {1}", sc.x, 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 inherit from sealed class 'SealedClass'.

No comments:

Post a Comment