c sharp

What is sealed class in C#

In C# a sealed class does not inherit from an additional class. It uses sealed classes to prohibit a class from inheriting and ensure its behavior and functionality stay consistent throughout the program. In this post, we will further explore and analyze sealed class in C# as well as implement it using example programs.

What is sealed class in C#?

A sealed class in C# programming language is not inherited by any of the other classes. When a class is declared as sealed, it signifies that it has been finalized and can no longer be changed.

Syntax
In C#, the syntax for declaring a sealed class is as shown below:

sealed class ClassName
{
  //class members and method
}

Now, let’s see an example of a sealed class in C# programming.

Example: Simple Program of Sealed Class in C#
In this example program, we create a sealed class name as Sealed_Class, which includes a function called Message() that just prints a message to the console. To display the message, we create a new instance of the SealedClass and invoke its Message function in the Main method.

using System;

sealed class Sealed_Class
{
    public void Message()
    {
        Console.WriteLine("This is an example program of sealed class in C#");
    }
}
class MyProgram
{
    static void Main()
    {
        Sealed_Class obj = new Sealed_Class();
        obj.Message();
    }
}

In the above, the class named Sealed_Class is a sealed class that we can’t derive from, so it can’t be inherited by another class. The output of the above-implemented code is shown below:

Note: Sealing a class is important when you wish to ensure that a class’s functionality remains consistent throughout the program. As other classes continue to inherit from a sealed class. Furthermore, sealed classes can be generated and used in the same way as any other class. The sole distinction is that these cannot be inherited.

Conclusion

A sealed class in C# cannot be modified or inherited. It prevents another change or extension of the class, which is essential when you wish to ensure that a class’s behavior and functionality remain consistent throughout the program. In the above writing, you have simply seen an example of a sealed class that is used in the C# program.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.