Author Topic: Sealed Classes And Methods In C#  (Read 9706 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Sealed Classes And Methods In C#
« on: February 14, 2009, 12:58:13 AM »
Sealed Classes And Methods In C#

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.

In C# structs are implicitly sealed; therefore, they cannot be inherited.

Code: [Select]
using System;
sealed class MyClass
{
   public int x;
   public int y;
}

class MainClass
{
   public static void Main()
   {
      MyClass mC = new MyClass();
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
   }
}
In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:

class MyDerivedC: MyClass {} // Error

You will get the error message:
'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.

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.

Code: [Select]
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();
   }
}