[Previous] [Contents] [Next]

Sealed Classes


If you want to make sure that a class can never be used as a base class, you use the sealed modifier when defining the class. The only restriction is that an abstract class cannot be used as a sealed class because by their nature abstract classes are meant to be used as base classes. Another point to make is that although the purpose of a sealed class is to prevent unintended derivation, certain run-time optimizations are enabled as a result of defining a class as sealed. Specifically, because the compiler guarantees that the class can never have any derived classes, it's possible to transform virtual function member invocations on sealed class instances into nonvirtual invocations. Here's an example of sealing a class: -

using System;
sealed class MyPoint
{
    public MyPoint(int x,int y)
    {
        this.x =x;
        this.y =y;
    }

    private int X;
    public int x
    {
        get
        {
            return this.X;
        }
        set
        {
            this.X =value;
        }
    }

    private int Y;
    public int y
    {
        get
        {
            return this.Y;
        }
        set
        {
            this.Y = value;
        }
    }
}

class SealedApp
{
    public static void Main()
    {
        MyPoint pt = new MyPoint(6,16);
        Console.WriteLine("x = {0}, y = {1}", pt.x, pt.y);
    }
}

Note that I used the private access modifier on the internal class members X and Y. Using the protected modifier would result in a warning from the compiler because of the fact that protected members are visible to derived classes and, as you now know, sealed classes don't have any derived classes.

[Previous] [Contents] [Next]