Sealed Class in .NET C#: Syntax, Usage, and Example

Introduction

Users are prevented from inheriting a class by using sealed classes. The sealed keyword can be used to seal a class. The keyword informs the compiler that an extension of the class is not possible because it is sealed. A sealed class cannot be used to create another class.

A sealed class has the syntax shown below.

sealed class class_name
{
    // data members
    // methods
    ...
    ...
    ...
}

Additionally, a method can be sealed, in which case it becomes impervious to override attempts. In the classes from which they have been inherited, a method may, however, be sealed. A method must be declared as virtual in its base class in order to be declared as sealed.

A sealed class in C# is defined by the class definition that follows.

public sealed class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public DateTime BirthDate { get; set; }

    public int CalculateAge()
    {
        return DateTime.UtcNow.Year - BirthDate.Year;
    }
    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendLine($"{nameof(Id)} - {Id}, ");
        sb.AppendLine($"{nameof(FirstName)} - {FirstName}, ");
        sb.AppendLine($"{nameof(LastName)} - {LastName}, ");
        sb.AppendLine($"{nameof(BirthDate)} - {BirthDate}");

        return sb.ToString();
    }
}
var student = new Student
{
    Id = 1,
    FirstName = "Jaimin",
    LastName = "Shethiya",
    BirthDate = new DateTime(1990, 10, 5)
};

var age = student.CalculateAge();
Console.WriteLine(student.ToString());
Console.WriteLine($"\nAge: {age}");

Date time

It will now display an error saying that "It cannot be derived from a Sealed class" if it attempts to inherit a class from a sealed class.

Sealed class

Here is the show-sealed method example.

public class Addition
{
    public virtual int Add(int a, int b)
    {
        return a + b;
    }
}
public class Add1 : Addition
{
    public sealed override int Add(int a, int b)
    {
        return base.Add(a, b);
    }
}
var addition = new Addition();
var result = addition.Add(10, 20);

Console.WriteLine("{0} - {1}", nameof(result), result);

var add = new Add1();
result = add.Add(13, 34);

Console.WriteLine("\n{0} - {1}", nameof(result), result);

Addition

Things to keep in mind when using C#'s sealed class?

An abstract class is quite different from a sealed class.

There cannot be any abstract methods in the sealed class.

It ought to be the class at the bottom of the inheritance hierarchy.

It is never possible to utilize a sealed class as a base class.

Specifically, the sealed class is used to prevent additional inheritance.

It is possible to use the keyword sealed with properties, instance methods, and classes.

We learned the new technique and evolved together.

Happy coding!