Sealed Classes And Methods In C#
The sealed modifier is used to preventderivation from a class. An error occurs if a sealed class is specifiedas the base class of another class. A sealed class cannot also be anabstract class.
The sealed modifier isprimarily used to prevent unintended derivation, but it also enablescertain run-time optimizations. In particular, because a sealed classis known to never have any derived classes, it is possible to transformvirtual function member invocations on sealed class instances intonon-virtual invocations.
In C# structs are implicitly sealed; therefore, they cannot be inherited.
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 declarethe overrided method as sealed as shown below. By declaring it assealed, 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();
}
}
Conclusion
I've given you enough information to usesealed classes and methods in your code and shown you some examples.The feedback is always welcome. Feel free to contact me for anyquestions or comments you may have about this article atrajeshvs@msn.com.




19. Apr, 2006 by 







Thanks!! Very usefull