Over a million developers have joined DZone.

Using Sealed in CSharp


Another potentially useful but not very popular keyword in CSharp is the sealed keyword.  While not a keyword that you will need to use often, it is a critical keyword for framework developers who want to have tighter control over how their classes get used.[img_assist|nid=6421|title=|desc=|link=none|align=right|width=244|height=184]

The two primary uses of the sealed keyword are as they apply to the class and as they are applied to elements of the class.

To start with the easiest first, we will apply sealed to the class.  You would applied sealed to a class when you want to create a class that no one else can inherit.  The string class is one such class.

class dmbcllc_com

sealed class blog_dmbcllc_com : dmbcllc_com

In the example above, the class dmbcllc_com can be used and inherited from anyone who can access it while blog_dmbcllc_com can only be used but can not be inherited from since we have sealed it.

Notice that the sealed keyword comes before the class keyword.

You might also apply the sealed keyword to virtual functions that you are overriding in a child class.  This has the effect of allowing you to prevent the virtual function from being overridden in the child class past the class where it has been sealed.

class dmbcllc_com
public virtual Foo() {}

class blog_dmbcllc_com : dmbcllc_com
sealed public override Foo() {}

class errorClass : blog_dmbcllc_com
public override Foo() {}

In the example above, errorClass.Foo() will cause a compile error because we are trying to override a method that has been sealed in the class above it.

You should be careful when using the sealed keyword that you do not unnecessarily seal off classes or methods simply because you can. You may end up backing yourself into a corner. It is possible to protect a class so much that it becomes completely unusable. One place I’ve seen this happen before is in the Java classes that were used to render HTML. The problem was ultimately fixed, but the initial implementation made it so that no one but the guys who wrote the classes could use them.

Seal classes and methods only when leaving them unsealed will be more dangerous than sealing them.




The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}