Sealed Class

Introduction:
This article explains how to create and use a sealed class using C#. We will also review why programming gurus use sealed classes in their code and products.

Sealed classes cannot be derived from. Does the sealed keyword improve the performance of method calls? This C# keyword prevents derivation. And it has an impact on performance in some contexts.

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

The following class definition defines a sealed class in C#:


// Sealed class

sealed class SealedClass

{


}


Example:

using System;

/// <summary>
/// Example interface.
/// </summary>
interface ITest
{
    /// <summary>
    /// Method required by the interface.
    /// </summary>
    int GetNumber();
}

/// <summary>
/// Non-sealed class that implements an interface.
/// </summary>
class TestA : ITest
{
    /// <summary>
    /// Interface implementation.
    /// </summary>
    public int GetNumber()
    {
 return 1;
    }
}

/// <summary>
/// Sealed class that implements an interface.
/// </summary>
sealed class TestB : ITest
{
    /// <summary>
    /// Interface implementation.
    /// </summary>
    public int GetNumber()
    {
 return 2;
    }
}

class Program
{
    static void Main()
    {
 ITest test1 = new TestA(); // Regular class
 ITest test2 = new TestB(); // Sealed instantiation
 Console.WriteLine(test1.GetNumber()); // TestA.GetNumber
 Console.WriteLine(test2.GetNumber()); // TestB.GetNumber
    }
} 
 
 Output
 1  
 2

Why Sealed Classes? 
We just saw how to create and use a sealed class. The main purpose of a sealed class is to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the "Pens" and "Brushes" classes of the "System.Drawing" namespace.

The Pens class represents the pens for standard colors. This class has only static members. For example, "Pens.Blue" represents a pen with the blue color. Similarly, the "Brushes" class represents standard brushes. "Brushes.Blue" represents a brush with blue color.

So when you're designing your application, you may keep in mind that you have sealed classes to seal the user's boundaries. 
Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment