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.
Continues…
Pages: 1 2












Thanks!! Very usefull