Wednesday, June 24, 2009

SEALED CLASS in .NET

The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.

What is a sealed class? 


It is a class, which cannot be subclassed. it is a good practice to mark your classes as sealed, if you do not intend them to be subclassed.

The two primary uses of the sealed keyword are as they apply to the class and as they are applied to elements of the class.You might also apply the sealed keyword to virtual functions that you are overriding in a child class.  This has the effect of allowing you to prevent the virtual function from being overridden in the child class past the class where it has been sealed.

// 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(4, 5);
              Console.WriteLine("Total = " + total.ToString());
         }


// Sealed class
sealed class SealedClass
{
       public int Add(int x, int y)
       {
           return x + y;
       }


In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.  

using System;
class MyClass1 
{
   public int x; 
   public int y;

   public virtual void Method()
   {
 Console.WriteLine("virtual method");
   }
}

class MyClass : MyClass1
{
   public override sealed void Method()
   {
 Console.WriteLine("sealed method");
   } 
}

class MainClass 
{
   public static void Main() 
   {
      MyClass1 mC = new MyClass(); 
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); 
      mC.Method();
   }
}