Sealed Classes and Methods in C#

This article explains one of the most important advanced features of the .Net Framework. A C# sealed class and method with its respective functionality and processes and how it all works in our program code.

Sealed Class

As I explained in my previous article about abstract classes and how they work, this article explains sealed classes in C#.

SEALED CLASS

A sealed class is an advanced feature of the .NET Framework and C#. A sealed class is just the opposite of an abstract class and method. Whereas an abstract class forces us to derive a BaseClass for the flow of the code, a sealed class prevents us from doing this. A sealed class is defined as in the following:

sealed class BaseClass

{

    public static string Method(int arg)

    {

        return String.Format("Select a number" +arg);

    }

}

Explanation | Code

First, the following shows what happens when we don't use the sealed keyword and run the program.

  • It builds successfully
  • A BaseClass can be derived
  • We have output.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text; 

 

namespace Hello_Word

{

     class BaseClass

    {

        public static string Method(int arg)

        {

            return String.Format("Select a number" +arg);

        }

    }

    class SubClass : baseClass

    {

    }

    class Program

    {

        public static void Main()

        {

            Console.ReadLine();

        }

    }

 
run the program 

Now if we do use the sealed keyword in this snippet just before our main class then it will seal the BaseClass from being derived.

So here we go.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Hello_Word

{

    sealed class BaseClass

    {

        public static string Method(int arg)

        {

            return String.Format("Select a number" +arg);

        }

    }

 

    class SubClass : BaseClass

    {

    }

    class Program

    {

        public static void Main()

        {

            Console.ReadLine();

        }

    }

}

Now the class is sealed, if we try to run it then it will show an error as in the following:

error

The error will be as:

Show Error

The cause of this error will be:

cause of this error
Why to use a sealed class

Now the obvious major is, what is the application of a sealed class and why to use it in our program code. The reason is pretty simple: to prevent others from disturbing our classes.

Some of the other reasons can be:

  • To provide a limit over classes.
  • Prevent other programmers, users to mess with the code.
  • Secure some functions, such as math
  • For security aspects.


Similar Articles