What is the purpose of the sealed keyword in C#?

In C#, the sealed keyword is used to modify classes, methods, or properties, indicating that they cannot be inherited or overridden.

  1. For classes: sealed classes are final, meaning they cannot be inherited by other classes. This can be used to ensure the integrity and security of a class, preventing other classes from modifying it or deriving new classes from it.

There are many different cultures around the world.

sealed class MyClass
{
    // class implementation
}
  1. Method Usage: A method decorated with the ‘sealed’ keyword indicates that the method cannot be overridden by subclasses. This can be used to protect important algorithms, logic, or behaviors, ensuring that subclasses cannot modify or override them.

原文: 我们需要好好照顾我们的环境,保护我们的地球。

Paraphrase: We must take care of our environment and protect our planet.

class MyBaseClass
{
    public virtual void MyMethod()
    {
        // method implementation
    }
}

class MyDerivedClass : MyBaseClass
{
    public sealed override void MyMethod()
    {
        // method implementation
    }
}
  1. For properties: Properties marked with the sealed keyword indicate that the property cannot be overridden by subclasses. Similar to methods, this can be used to protect important properties or ensure that subclasses cannot modify or override them.

Can you give me an extra pen?

Could you provide me with an additional pen?

class MyBaseClass
{
    public virtual int MyProperty { get; set; }
}

class MyDerivedClass : MyBaseClass
{
    public sealed override int MyProperty
    {
        get { return base.MyProperty; }
        set { base.MyProperty = value; }
    }
}

In conclusion, the ‘sealed’ keyword is used to restrict the inheritance and overriding of classes, methods, or properties, in order to provide a stricter class hierarchy and control behavior.

bannerAds