Sealed Class in C#

In this post,we will learn about Sealed Class in C# with an example.I will also review why programming expert use sealed classes in their code and products.

Description:

In my previous posts I have explained various topics like Continue keyword in C#.Net, Difference between string and StringBuilder in C#, Difference between a struct and a class in C#, Boxing & Unboxing in C# ,Dynamic Type In C#, Named Arguments In C#, Basics Of Pointers In C#, Get site visitor count in asp.net, Convert generic list to datatable in Asp.Net C#.Net, Abstract Class in C# with Example.



Now in this post, I will explain about Sealed Class in C# with appropriate example.

Sealed classes are used to limit(restrict) the inheritance feature of oop.If class is defined as a sealed class, the class cannot be inherited. 

In C#, the sealed modifier or keyword is used to define a class as sealed. In Visual Basic .NET the NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error and mark it as invalid.

Now create Console Application in Visual Studio and write below lines of code in it.

using System;
using System.Collections;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            SealedClass sealedCls = new SealedClass();

            int total = sealedCls.AddNumber(7, 3);

            Console.WriteLine("Sum = " + total.ToString());
            Console.ReadLine();
        }
    }
    sealed class SealedClass
    {
        public int AddNumber(int x, int y)
        {
            return x + y;
        }
    }  
}

Why Sealed Classes?

The basic intesnsion of a sealed class is to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members.

Summary

I hope you got an idea about Sealed Class in C#.
I would like to have feedback from blog my readers.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website