Sealed Classes In C# Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Sealed Classes in C#

Sealed Classes in C#: Detailed Explanation and Important Information

Introduction

Syntax

The syntax for a sealed class is straightforward. You simply need to place the sealed keyword before the class declaration.

sealed class SealedClassName
{
    // class members
}

Why Use Sealed Classes?

  • Security: Prevents sensitive classes, such as security-sensitive classes, from being subclassed.
  • Performance: Since sealed classes cannot be overridden, they allow the compiler to inline method calls, which can result in better performance.
  • Final Design: When a class is sealed, it indicates that the class is final and that no further customization through inheritance can occur. This is particularly useful in frameworks where certain classes are designed as final components.

Use Cases

  1. Security: Ensuring that critical classes cannot be tampered with.
  2. Framework Design: Designing frameworks where certain classes should not be altered.
  3. Performance Optimization: Sealing critical classes to allow for performance optimizations through method inlining.

Example

Let’s consider an example where we have a BankDetails class that holds sensitive information about a bank account. We want to ensure that this class cannot be subclassed to prevent malicious code from extending this class to capture sensitive data.

sealed class BankDetails
{
    public string AccountNumber { get; private set; }
    public string OwnerName { get; private set; }

    public BankDetails(string accountNumber, string ownerName)
    {
        AccountNumber = accountNumber;
        OwnerName = ownerName;
    }
}

In this example, BankDetails is a sealed class, so attempts to inherit from it will result in a compile-time error.

Sealed Methods

It's worth noting that methods can also be sealed in C#. A sealed method overrides a virtual method and prevents further overriding in derived classes.

class BaseClass
{
    public virtual void Display()
    {
        Console.WriteLine("Display method in BaseClass");
    }
}

class DerivedClass : BaseClass
{
    public sealed override void Display()
    {
        Console.WriteLine("Display method in DerivedClass");
    }
}

In the above code, Display in DerivedClass is sealed and cannot be overridden in any further derived classes.

Important Points

  • Sealed Classes: Cannot be inherited.
  • Sealed Methods: Cannot be overridden in derived classes.
  • Virtual Methods: Can be overridden unless they are sealed.
  • Performance: Sealing classes can lead to performance improvements due to method inlining.
  • Security: Sealing classes is a security measure to prevent misuse.

Limitations

  • If a class is sealed, it restricts future extensibility.
  • Overuse of sealed classes might lead to a rigid codebase, making it difficult to adapt to new requirements.

Best Practices

  • Use sealed classes judiciously, especially in frameworks to ensure security and performance.
  • Avoid sealing classes when you anticipate needing to extend them in future versions.

By understanding the use cases, performance benefits, and limitations of sealed classes in C#, developers can make informed decisions about their use to build robust and secure applications.

Conclusion

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Sealed Classes in C#

Complete Examples, Step by Step for Beginners: Sealed Classes in C#

Step 1: Creating a Simple Class

Let's start by creating a simple class that we'll later seal. This class will represent a Vehicle and will have a method to display its type.

using System;

public class Vehicle
{
    public void DisplayType()
    {
        Console.WriteLine("This is a generic vehicle.");
    }
}

Step 2: Sealing the Class

Now, we will modify our Vehicle class to be sealed using the sealed keyword. This will prevent any other classes from inheriting from it.

using System;

public sealed class Vehicle
{
    public void DisplayType()
    {
        Console.WriteLine("This is a generic vehicle.");
    }
}

Step 3: Attempting to Inherit from the Sealed Class (Error Example)

Let's see what happens if we try to inherit from the sealed Vehicle class.

public class Car : Vehicle // This will cause a compiler error
{
    public void DisplayCarInfo()
    {
        Console.WriteLine("This is a car.");
    }
}

If you try to compile the above code, the compiler will throw an error:

error CS0509: 'Car': cannot derive from sealed type 'Vehicle'

Step 4: Using the Sealed Class

Since we cannot inherit from a sealed class, we can only use it directly or through composition. Let's create an instance of the sealed Vehicle class and call its method.

using System;

public sealed class Vehicle
{
    public void DisplayType()
    {
        Console.WriteLine("This is a generic vehicle.");
    }
}

public class Program
{
    public static void Main()
    {
        Vehicle myVehicle = new Vehicle();
        myVehicle.DisplayType();
    }
}

Output:

This is a generic vehicle.

Step 5: Real-World Use Case for Sealed Classes

Sealed classes are often used in scenarios where you have a well-defined and complete set of behaviors, and you don’t want any deviation from them. For example, a core library for banking operations might have a sealed class for sensitive operations that should not be altered.

using System;

public sealed class BankTransaction
{
    public void PerformTransaction(double amount)
    {
        Console.WriteLine($"Performing transaction for amount: {amount}.");
    }

    public void VerifyTransaction()
    {
        Console.WriteLine("Verifying transaction...");
    }

    public void CompleteTransaction()
    {
        Console.WriteLine("Transaction completed.");
    }
}

public class Program
{
    public static void Main()
    {
        BankTransaction transaction = new BankTransaction();
        transaction.PerformTransaction(1000.00);
        transaction.VerifyTransaction();
        transaction.CompleteTransaction();
    }
}

Output:

Top 10 Interview Questions & Answers on Sealed Classes in C#

1. What is a Sealed Class in C#?

A sealed class in C# is a class that prevents other classes from inheriting from it. When you define a class as sealed, you effectively lock it down for further extension. The sealed keyword is used to achieve this.

public sealed class MySealedClass {
    // class members
}

2. Why Would You Use a Sealed Class?

  • Security: Sealing a class can prevent inheritance by malicious code that may want to override methods with potentially harmful behavior.
  • Code Optimization: Sealed classes can sometimes lead to performance optimizations because the compiler knows that no derived classes will override the sealed class's methods.
  • Complete Design: It ensures that a class’s design is complete and should not be extended. For instance, fundamental system classes like String, Int32, etc., are sealed.

3. Can an Abstract Class Be Sealed?

No, an abstract class cannot be sealed in C#. An abstract class is intended to be a base class for other classes, meaning it must be inherited to be used, whereas a sealed class is intended to prevent inheritance.

4. Can a Sealed Class Contain Abstract Methods?

No, a sealed class cannot contain abstract methods. If a class is sealed, all its methods must have concrete implementations because it cannot be inherited and overridden.

5. Can a Nested Class Be Sealed?

Yes, a nested class can be sealed. The behavior of a sealed nested class is just like a regular sealed class—it cannot be inherited.

public class OuterClass {
    public sealed class InnerClass {
        // class members
    }
}

6. How Does Sealing a Class Affect Performance?

Sealing a class can allow the compiler to optimize method calls on sealed classes at compile time using inline expansions. However, the performance gain is usually negligible unless the method is called very frequently and has a small footprint.

7. Can Sealed Classes Override Methods?

Yes, sealed classes can override methods. The only restriction is that they cannot then be further overridden by derived classes since they are sealed.

public class BaseClass {
    public virtual void MyMethod() { }
}

public sealed class SealedDerived : BaseClass {
    public override void MyMethod() { 
        Console.WriteLine("Overridden in sealed class"); 
    }
}

8. Can a Method Be Sealed in C#?

No, individual methods cannot be sealed in C#. Sealing applies to entire classes. However, derived classes can use the sealed keyword to prevent overriding methods that were marked as virtual or override in their base class.

public class BaseClass {
    public virtual void MyMethod() { }
}

public class DerivedClass : BaseClass {
    public sealed override void MyMethod() { }
}

public class AnotherClass : DerivedClass {
   // Error: MyMethod cannot be overridden because it is sealed
   // public override void MyMethod() { }
}

9. What Are the Limitations of Using a Sealed Class?

  • Flexibility: Once a class is sealed, you cannot extend it in the future if you need more specific behaviors.
  • Design Change: Sealing a class prematurely can prevent future enhancements and changes to your design.

10. Is there a Way to Determine if a Class is Sealed at Runtime?

Yes, you can determine if a class is sealed at runtime using reflection. Specifically, you can check the IsSealed property of the System.Type class.

You May Like This Related .NET Topic

Login to post a comment.