C Sharp

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.

Summary

The concept of classes and their relationship to objects is the basis for the idea of programming based on objects. The object-oriented features of C# build on a heritage handed down from C++ and are molded and enhanced by the features of the .NET Framework. In managed systems like the Common Language Runtime, resource management is a subject of great concern to developers. The CLR strives to free programmers from the drudgery of reference counting through garbage collection based on deterministic finalization. Also, inheritance in C# is handled differently than in C++. Although only single inheritance is supported, developers can still reap some of the benefits of multiple inheritance by implementing multiple interfaces.

by BrainBellupdated
Advertisement: