C# Sealed
To apply restrictions on the class and the method in C#, the sealed keyword is used. When created, a sealed class can’t be derived. However, a sealed method can’t be overridden when created. Structs can’t be inherited, because they are implicitly sealed.
C# Sealed class:
Any class can’t derive a sealed class in C# when created.
Example:
using System; sealed public class Flower{ public void color() { Console.WriteLine("White Flower!!"); } } public class Lily: Flower { public void white() { Console.WriteLine("White Lily!!"); } } public class TestSealed { public static void Main() { Lily f = new Lily(); f.color(); f.white(); } } |
Output:
Explanation:
In the above example, we are displaying the use and behavior of the sealed class in C#.
C# Sealed method:
A sealed method can’t be overridden further when created and is thus used with the override keyword in C#.
Example:
using System; public class Flower{ public virtual void color() { Console.WriteLine("...Rose"); } public virtual void symbol() { Console.WriteLine("Symbolizes..."); } } public class RedRose: Flower { public override void color() { Console.WriteLine("Red Rose!!"); } public sealed override void symbol() { Console.WriteLine("Symbolizes Love"); } } public class YellowRose : RedRose { public override void color() { Console.WriteLine("Yellow Rose!!"); } public override void symbol() { Console.WriteLine("Symbolizes Friendship!!"); } } public class TestSealed { public static void Main() { YellowRose y = new YellowRose(); y.color(); y.symbol(); } } |
Output:
Explanation:
In the above example, we are displaying the use and behavior of the sealed method in C#.
Local variables:
In C# local variables can’t be sealed.
Example:
using System; public class TestSealed { public static void Main() { sealed float i = 2.5; i--; Console.WriteLine(i); } } |
Output:
Explanation:
In the above example, we are displaying the effect of the sealed keyword on the local variables in C#. It is not possible to seal the local variables in C# and hence an error will be generated.