C# Sealed Class

What is sealed class?

You can use the sealed keyword to create a sealed class. A sealed class cannot be used as a base class. In other words, a sealed class cannot be inherited. Now, let's create an application named MySealedClass that shows how a class can be declared as sealed.

Note : Sealed class can not be inherited.

Example of Sealed class

using System;
using System.Collections.Generic;
using sytem.Linq;
using System.Text;
namespace MySealedClass
  sealed class MyClass
    string fName;
    string lName;
    int Age;
    public void GetDetails()
       Console.Write("Enter Your First Name:");
       Console.Write("Enter Your Last Name:");
       Console.Write("Enter Your Age:");
     public void ShowDetail()
       Console.WriteLine(fName +" "+ lName +" you are "+Age+" Years Old");
//Following lines show compiler error as a Sealed class cannot be inherited
   classDerived : MyClass
   class MainClass
      public static void Main(string[] args)
         MyClass obj=new MyClass();
         Console.Write("\n Press Enter to quit....");

We have created a sealed class, named MyClass, by using the sealed keyword. This class contains two methods, GetDetail() and ShowDetail(), to take the input from a user and show the details, respectively, Next, we have created an object of the MyClass class in the Main() method of the MainClass class. Finally, we have invoked the GetDetail() and ShowDetail() methods.

Output of Sealed class

Enter Your First Name: Chandan
Enter Your Last Name: Payra
Enter Your Age:23
Chandan Payra you are 23 Years Old

Press ENTER to quit...

Write a comment

Name Email Message