Friday 14 December 2012

Sealed Classes in c# , .Net


Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. 
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET,NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error. 
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.  

The following class definition defines a sealed class in C#: 
// Sealed class
sealed class SealedClass
{
    } 

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.
 

using System;
class Class1
{
    static void Main(string[] args)
    {
        SealedClass sealedCls = new SealedClass();
        int total = sealedCls.Add(45);
        Console.WriteLine("Total = " + total.ToString());
    }
}
// Sealed class
sealed class SealedClass
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}  


Why Sealed Classes?
 

We just saw how to create and use a sealed class. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawingnamespace. 
The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color. 
So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries. 
In the next article of this series, I will discuss some usage of abstract classes. 

No comments:

Post a Comment