C# - The Sealed Keyword

The sealed Keyword in C#

The sealed keyword  in C# is a powerful construct that is used to restrict inheritance. It prevents other classes from deriving from a class or prevents a method from being overridden further in a derived class. This concept plays a crucial role in enforcing encapsulation, optimizing performance, and securing class designs. In this guide, we will explore the sealed keyword in-depth, examining its use in classes, methods, real-world applications, and best practices.

Understanding the sealed Keyword

The sealed keyword can be applied in two primary contexts:

  • To a class, preventing it from being inherited.
  • To a method in a derived class, preventing further overriding.

Why Seal Classes or Methods?

There are several reasons for using the sealed keyword:

  • To maintain control over a class’s behavior.
  • To improve performance by allowing method inlining.
  • To prevent misuse of classes that are not designed for inheritance.
  • To signal the developer’s intention that no further derivation is allowed.

Using sealed with Classes

When a class is marked as sealed, it cannot be used as a base class. This is useful for utility, helper, or internal classes that should not be extended.

Syntax

sealed class FinalClass
{
    public void Display()
    {
        Console.WriteLine("This is a sealed class.");
    }
}
    

Attempting to Inherit a Sealed Class

// This will cause a compile-time error
class DerivedClass : FinalClass
{
}
    

Trying to inherit from a sealed class will result in a compilation error: "Cannot derive from sealed type 'FinalClass'".

Using sealed with Methods

A method can be marked as sealed when it is part of a class hierarchy and has been overridden. Marking a method as sealed ensures that no further overriding can occur beyond the current class.

Syntax

class Base
{
    public virtual void Show()
    {
        Console.WriteLine("Base implementation");
    }
}

class Derived : Base
{
    public sealed override void Show()
    {
        Console.WriteLine("Derived sealed implementation");
    }
}

class SubDerived : Derived
{
    // Compile-time error: cannot override sealed method
    // public override void Show()
    // {
    //     Console.WriteLine("Attempting to override");
    // }
}
    

In this example, the method Show() in the Derived class is sealed and thus cannot be overridden in the SubDerived class.

Practical Applications of Sealed Classes

Security and Integrity

Sealing a class can protect critical business logic from being altered through inheritance. This ensures that the functionality remains consistent and secure.

Performance Optimization

Sealed methods are not subject to override, which allows the JIT compiler to optimize the method calls more aggressively through techniques like inlining.

Framework Design

In large frameworks, base classes are often sealed to prevent clients from extending them incorrectly, which could lead to maintenance challenges.

Utility Classes

Utility or static classes are often sealed to indicate that they are not intended to be inherited.

Example: Sealed Class in a Banking Application

sealed class BankTransaction
{
    public void ProcessTransaction()
    {
        Console.WriteLine("Processing transaction securely.");
    }
}
    

By sealing the BankTransaction class, the developer ensures that no other class can alter the logic through inheritance, thus preserving the security and correctness of the implementation.

Example: Sealed Method in Logging System

class Logger
{
    public virtual void Log(string message)
    {
        Console.WriteLine($"Base log: {message}");
    }
}

class FileLogger : Logger
{
    public sealed override void Log(string message)
    {
        Console.WriteLine($"File log: {message}");
    }
}
    

Here, the log method in FileLogger is sealed to prevent further customization, which can be important in compliance or audit scenarios.

Sealed vs Abstract vs Virtual

Keyword Description Can be Inherited? Can be Overridden?
sealed Prevents inheritance or overriding No No
abstract Must be overridden in derived class Yes Must override
virtual May be overridden in derived class Yes Optional

Best Practices When Using sealed

  • Seal classes that are not intended for extension.
  • Seal methods to lock down specific behavior when needed.
  • Document the reasoning behind sealing for clarity to other developers.
  • Avoid overusing sealed in APIs intended for extensibility.

Sealed Keyword in Combination with Other Modifiers

Sealed and Static

A class marked static is implicitly sealed. You cannot inherit from a static class.

static class Utility
{
    public static void DoWork()
    {
        Console.WriteLine("Work done.");
    }
}
    

Sealed and Abstract

Not allowed. You cannot mark a class as both sealed and abstract because it is a contradiction. An abstract class is meant to be extended, while a sealed class cannot be extended.

Real-World Examples of Sealed Classes in .NET

Many .NET framework classes are sealed. Examples include:

  • System.String
  • System.Int32
  • System.DateTime
  • System.Math (static and implicitly sealed)
  • System.Convert

These classes are sealed to prevent modification of core behavior, improve performance, and maintain reliability across the .NET ecosystem.

Performance Considerations

Sealing methods or classes can provide small performance gains in tight loops or performance-critical applications, because:

  • JIT (Just-in-Time) compiler can optimize calls more aggressively.
  • Virtual method table lookups are avoided for sealed methods.
  • Improved predictability for compilers and developers.

When Not to Use Sealed

  • When designing base classes meant for extension.
  • When future changes might require subclassing.
  • When writing APIs or frameworks for third-party usage.

Alternative: Internal Classes

Sometimes sealing is confused with access restriction. If you simply want to prevent use outside of an assembly, consider using the internal modifier instead of sealing the class.

internal class InternalClass
{
    // Accessible only within the same assembly
}
    

Refactoring Sealed Classes

If a class was sealed but later you decide to allow extension, simply remove the sealed keyword. However, be cautious:

  • Review how the class was used.
  • Ensure documentation reflects the change.
  • Write unit tests to protect against unexpected behaviors.

The sealed keyword in C# is a vital part of the language’s type safety and design principles. It provides developers the ability to finalize class hierarchies or lock down method behavior for security, clarity, and performance. Used correctly, it helps in maintaining strong object-oriented design by explicitly expressing intent and boundaries in your code.

  • Use sealed classes to prevent inheritance where necessary.
  • Use sealed methods to finalize behavior in a hierarchy.
  • Understand when sealing aids performance versus when it hinders extensibility.
  • Recognize sealed classes in the .NET library as trusted and optimized core components.

By mastering the use of the sealed keyword, developers can produce safer, more maintainable, and performant code.

logo

C#

Beginner 5 Hours

The sealed Keyword in C#

The sealed keyword  in C# is a powerful construct that is used to restrict inheritance. It prevents other classes from deriving from a class or prevents a method from being overridden further in a derived class. This concept plays a crucial role in enforcing encapsulation, optimizing performance, and securing class designs. In this guide, we will explore the sealed keyword in-depth, examining its use in classes, methods, real-world applications, and best practices.

Understanding the sealed Keyword

The sealed keyword can be applied in two primary contexts:

  • To a class, preventing it from being inherited.
  • To a method in a derived class, preventing further overriding.

Why Seal Classes or Methods?

There are several reasons for using the sealed keyword:

  • To maintain control over a class’s behavior.
  • To improve performance by allowing method inlining.
  • To prevent misuse of classes that are not designed for inheritance.
  • To signal the developer’s intention that no further derivation is allowed.

Using sealed with Classes

When a class is marked as sealed, it cannot be used as a base class. This is useful for utility, helper, or internal classes that should not be extended.

Syntax

sealed class FinalClass
{
    public void Display()
    {
        Console.WriteLine("This is a sealed class.");
    }
}
    

Attempting to Inherit a Sealed Class

// This will cause a compile-time error
class DerivedClass : FinalClass
{
}
    

Trying to inherit from a sealed class will result in a compilation error: "Cannot derive from sealed type 'FinalClass'".

Using sealed with Methods

A method can be marked as sealed when it is part of a class hierarchy and has been overridden. Marking a method as sealed ensures that no further overriding can occur beyond the current class.

Syntax

class Base
{
    public virtual void Show()
    {
        Console.WriteLine("Base implementation");
    }
}

class Derived : Base
{
    public sealed override void Show()
    {
        Console.WriteLine("Derived sealed implementation");
    }
}

class SubDerived : Derived
{
    // Compile-time error: cannot override sealed method
    // public override void Show()
    // {
    //     Console.WriteLine("Attempting to override");
    // }
}
    

In this example, the method Show() in the Derived class is sealed and thus cannot be overridden in the SubDerived class.

Practical Applications of Sealed Classes

Security and Integrity

Sealing a class can protect critical business logic from being altered through inheritance. This ensures that the functionality remains consistent and secure.

Performance Optimization

Sealed methods are not subject to override, which allows the JIT compiler to optimize the method calls more aggressively through techniques like inlining.

Framework Design

In large frameworks, base classes are often sealed to prevent clients from extending them incorrectly, which could lead to maintenance challenges.

Utility Classes

Utility or static classes are often sealed to indicate that they are not intended to be inherited.

Example: Sealed Class in a Banking Application

sealed class BankTransaction
{
    public void ProcessTransaction()
    {
        Console.WriteLine("Processing transaction securely.");
    }
}
    

By sealing the BankTransaction class, the developer ensures that no other class can alter the logic through inheritance, thus preserving the security and correctness of the implementation.

Example: Sealed Method in Logging System

class Logger
{
    public virtual void Log(string message)
    {
        Console.WriteLine($"Base log: {message}");
    }
}

class FileLogger : Logger
{
    public sealed override void Log(string message)
    {
        Console.WriteLine($"File log: {message}");
    }
}
    

Here, the log method in FileLogger is sealed to prevent further customization, which can be important in compliance or audit scenarios.

Sealed vs Abstract vs Virtual

Keyword Description Can be Inherited? Can be Overridden?
sealed Prevents inheritance or overriding No No
abstract Must be overridden in derived class Yes Must override
virtual May be overridden in derived class Yes Optional

Best Practices When Using sealed

  • Seal classes that are not intended for extension.
  • Seal methods to lock down specific behavior when needed.
  • Document the reasoning behind sealing for clarity to other developers.
  • Avoid overusing sealed in APIs intended for extensibility.

Sealed Keyword in Combination with Other Modifiers

Sealed and Static

A class marked static is implicitly sealed. You cannot inherit from a static class.

static class Utility
{
    public static void DoWork()
    {
        Console.WriteLine("Work done.");
    }
}
    

Sealed and Abstract

Not allowed. You cannot mark a class as both sealed and abstract because it is a contradiction. An abstract class is meant to be extended, while a sealed class cannot be extended.

Real-World Examples of Sealed Classes in .NET

Many .NET framework classes are sealed. Examples include:

  • System.String
  • System.Int32
  • System.DateTime
  • System.Math (static and implicitly sealed)
  • System.Convert

These classes are sealed to prevent modification of core behavior, improve performance, and maintain reliability across the .NET ecosystem.

Performance Considerations

Sealing methods or classes can provide small performance gains in tight loops or performance-critical applications, because:

  • JIT (Just-in-Time) compiler can optimize calls more aggressively.
  • Virtual method table lookups are avoided for sealed methods.
  • Improved predictability for compilers and developers.

When Not to Use Sealed

  • When designing base classes meant for extension.
  • When future changes might require subclassing.
  • When writing APIs or frameworks for third-party usage.

Alternative: Internal Classes

Sometimes sealing is confused with access restriction. If you simply want to prevent use outside of an assembly, consider using the internal modifier instead of sealing the class.

internal class InternalClass
{
    // Accessible only within the same assembly
}
    

Refactoring Sealed Classes

If a class was sealed but later you decide to allow extension, simply remove the sealed keyword. However, be cautious:

  • Review how the class was used.
  • Ensure documentation reflects the change.
  • Write unit tests to protect against unexpected behaviors.

The sealed keyword in C# is a vital part of the language’s type safety and design principles. It provides developers the ability to finalize class hierarchies or lock down method behavior for security, clarity, and performance. Used correctly, it helps in maintaining strong object-oriented design by explicitly expressing intent and boundaries in your code.

  • Use sealed classes to prevent inheritance where necessary.
  • Use sealed methods to finalize behavior in a hierarchy.
  • Understand when sealing aids performance versus when it hinders extensibility.
  • Recognize sealed classes in the .NET library as trusted and optimized core components.

By mastering the use of the sealed keyword, developers can produce safer, more maintainable, and performant code.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.


The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.


line

Copyrights © 2024 letsupdateskills All rights reserved