C# Sealed

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Sealed Members in C#

Preventing Further Inheritance:

The sealed keyword is used to prevent further inheritance of a class or the overriding of specific members.

// Sealed base class

public sealed class FinalBase

{

    // Class implementation

}

// Sealed method in a class

public class SealExample

{

    public sealed void SealedMethod()

    {

        // Method implementation

    }

}

Sealing a Class:

You can seal a class to prevent it from being used as a base class.

public sealed class FinalClass

{

    // Class implementation

}

Sealing a Method:

Sealing a method prevents it from being overridden by derived classes.

public class SealedExample

{

    public sealed void SealedMethod()

    {

        // Method implementation

    }

}

 

public class DerivedFromSealed : SealedExample

{

    // Attempting to override the sealed method will result in a compilation error

    // public override void SealedMethod() { /* … */ }

}

Best Practices:

– Design base classes carefully, ensuring they provide a meaningful abstraction.
– Avoid sealing base classes unless necessary for specific use cases.
– Seal classes or members when you want to ensure stability and prevent unintended modifications by derived classes.