Sealed Classes in C#

In this article, I will discuss how to create and use sealed classes in C# and .NET. We will also review why programming gurus use sealed classes in their real world applications.  
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. 
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET,NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, 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

{    } 

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error. 

using System;

class Class1

{

    static void Main(string[] args)

    {

        SealedClass sealedCls = new SealedClass();

        int total = sealedCls.Add(45);

        Console.WriteLine("Total = " + total.ToString());

    }

}

// Sealed class

sealed class SealedClass

{

    public int Add(int x, int y)

    {

        return x + y;

    }

}  

Why Sealed Classes?
 

We just saw how to create and use a sealed class. The main purpose of a sealed class 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.Drawingnamespace. 
The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The 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 user's boundaries. 
In the next article of this series, I will discuss some usage of abstract classes. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值