Curriculum
In C#, the sealed keyword is used to prevent further inheritance of a class or to prevent further overriding of a virtual method or property in a derived class. Once a class or method is marked as sealed, it cannot be inherited or overridden any further.
Here’s an example of using the sealed keyword to prevent further inheritance:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal is making a sound");
}
}
public sealed class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
// This will result in a compile-time error because we cannot inherit from a sealed class
public class Kitten : Cat
{
// ...
}
In this example, we have a base class Animal and a derived class Cat that overrides the MakeSound() method. The Cat class is marked as sealed, which means it cannot be further inherited by any other class.
If we try to create a new class Kitten that inherits from Cat, we will get a compile-time error because Cat is sealed and cannot be further inherited.
Here’s an example of using the sealed keyword to prevent further overriding of a virtual method:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal is making a sound");
}
}
public class Cat : Animal
{
public sealed override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
public class Kitten : Cat
{
// This will result in a compile-time error because we cannot override a sealed method
public override void MakeSound()
{
// ...
}
}
In this example, we have a base class Animal, a derived class Cat that overrides the MakeSound() method, and a further derived class Kitten that attempts to override the MakeSound() method again. However, the MakeSound() method in Cat is marked as sealed, which means it cannot be further overridden.
If we try to override the MakeSound() method again in the Kitten class, we will get a compile-time error because the method is sealed and cannot be further overridden.
In summary, the sealed keyword in C# is used to prevent further inheritance of a class or to prevent further overriding of a virtual method or property in a derived class. Once a class or method is marked as sealed, it cannot be inherited or overridden any further.