KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

C# Sealed Class

Introduction

A sealed class is a class that cannot be extended by other classes. Sealed classes provide security when you do not want other programmers to alter the implementation of a method(s). It is possible to seal only methods within a class but it is far more common to seal an entire class than methods.

Sealed class syntax

Sealed classes are defined using the sealed keyword.

sealed class SealedClass
{
    //do something
}

HERE,

  • the keyword sealed is used to define the class as sealed.

Practical Example

Create a new project CSharpSealedClass

Add a new class SealedClass.cs

Add the following code to SealedClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpSealedClass
{
    sealed class SealedClass
    {
        public void someMethod()
        {
            Console.WriteLine("Am a sealed class");
        }
    }
}

Add another new class SealedDerivedClass.cs

Add the following code to SealedDerivedClass.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpSealedClass
{
    class SealedDerivedClass : SealedClass
    {
    }
}

Press F6 on the keyboard to build the project.

You will get the following compile error.

'CSharpSealedClass.SealedDerivedClass': cannot derive from sealed type 'CSharpSealedClass.SealedClass'

You will get the above error because you are trying to inherit from a sealed class.

Comment the part that extends the sealed class as shown below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpSealedClass
{
    class SealedDerivedClass //: SealedClass
    {
    }
}

Press F6 on the keyboard.

The project will compile successfully. The sealed class can be just like any other ordinary class. The following code create an instance of a sealed class and executes the someMethod method that we defined in the sealed class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpSealedClass
{
    class Program
    {
        static void Main(string[] args)
        {
            SealedClass sealedClass = new SealedClass();
            sealedClass.someMethod();

            Console.ReadLine();
        }
    }
}

Press F5 on the keyboard.

The above code will produce the following results.

Am a sealed class

Summary

  • Sealed classes cannot be inherited
  • Sealed classes are used to prevent programmers using the class from overriding its behaviour
  • individual methods within a regular class can be sealed.

Tutorial History

Tutorial version 1: Date Published 2015-08-17