Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » Sealed Classes in C#

Sealed Classes in C#

In this article, I will discuss how to create and use sealed classes. I will also show you where programming gurus use sealed classes in their real world applications.

Author Rank :
Page Views : 144048
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



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(4, 5);

        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.Drawing namespace.
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.


Note: At the time of writing this article, C# language did not have static classes. Now C# has static classes.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
whay is the difference b/w interface and abstractclass by prakash On January 31, 2007
whay is the difference b/w interface and abstractclass..? some body pls..give me right answer... regrards.. Prakash
Reply | Email | Modify 
Re: whay is the difference b/w interface and abstractclass by Mahesh On February 1, 2007
An interface can have only definitions, no implementation. However, an abstract class can have definitions as well as implementation. For example, if you have an interface with a method called "AddNumbers", this method will have no code inside the method. In the case of abstract class, this method can have code inside it.
Reply | Email | Modify 
Why sealed keyword by a On September 23, 2007
Why would .NET framework designers take the trouble of providing a sealed keyword? What difference would it make even if the Pens class was not sealed and somebody derives it?
Reply | Email | Modify 
Re: Why sealed keyword by Mahesh On September 27, 2007

It makes a big difference when you are working on a large project (say 50 developers) and some of them are not "so good" developers are working on an application that uses a class library. As an architect, you do not want them to use some of the classes in the class library by the application developers b/c you are afraid they may use classes in a wrong way or these classes may affect resources and miuse of them will create serious problems. That's one reason I can see why Microsoft would implement sealed classes.

Reply | Email | Modify 
c# and java by arvind kumar On March 17, 2008
what is the differecnce between c# and java
Reply | Email | Modify 
what is proxy class? by shefali On September 30, 2008
what is proxy class and why we need to create it in WCF ???
Reply | Email | Modify 
Re: what is proxy class? by Mahesh On September 30, 2008
Please post your question on forums under WCF section. You will get a faster answer there. This area is for questions that are related to this article only.
Reply | Email | Modify 
difference b/w sealed and static? by Vinayaka On December 2, 2008
What is the difference between Sealed and Static class? When to use Sealed and static class?
Reply | Email | Modify 
Re: difference b/w sealed and static? by Mahesh On April 6, 2009
Sealed class you may read from this article.

A static class can only have ONE COPY in memory at anytime. So if multiple applications are calling same class, they are actually sharing the same memory space and variables. So whatever application changing values in a static class last, every caller applications have all changes the last app made.
Reply | Email | Modify 
Re: Re: difference b/w sealed and static? by Vinayaka On April 6, 2009
Thanks Mahesh for your reply.
That means Static Class and Sealed class have almost same functionality?
Reply | Email | Modify 
Re: Re: Re: difference b/w sealed and static? by Mahesh On April 6, 2009

The purpose of a sealed class is, when a component/library developer does not want it's user applications to call a class. This class is designed for library only.

Static classes on the other hand, are designed for user applications.

Reply | Email | Modify 
Re: Re: Re: Re: difference b/w sealed and static? by Jeremy On March 30, 2011
Yeah, you may not be able to derive or inherit a sealed class, but I can still do this: sealed class Data { public static string TestClass() { return "testdata"; } } Response.Write(Data.TestClass()); But if I get rid of the "static" keyword from the TestClass() method, I can do this: Response.Write(new Data().TestClass()); So, if I don't want someone developing a presentation layer to be able to access to the Data namespace, it seems like neither "sealed" nor "static" accomplishes this. I guess I'm still confused as to why I'd ever want to use these when, obviously, they're just as accessable as a non-static or non-sealed class.
Reply | Email | Modify 
Re: Re: difference b/w sealed and static? by Lawrence On March 22, 2010
Hi mahesh

I am Lawrence, u r going good were ever i search and if csharpcorner site comes the solution is yours, that s great and keep in touch with me and help me in doing some tasks. Can i have ur mail id. if u r ready to give it send it to my id lara_speedracing@yahoo.co.in.

Thank you
Lawrence
Reply | Email | Modify 
nice by chigicherla On February 17, 2009
pleaseilluistrate with good example.
Reply | Email | Modify 
nice by Manish On April 8, 2009

The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations.

In C# structs are implicitly sealed; therefore, they cannot be inherited.

using System;
sealed class MyClass 
{
   public int x; 
   public int y;
}

class MainClass 
{
   public static void Main() 
   {
      MyClass mC = new MyClass(); 
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); 
   }
}

In the preceding example, if you attempt to inherit from the sealed class by using a statement like this:

class MyDerivedC: MyClass {} // Error

You will get the error message:
'MyDerivedC' cannot inherit from sealed class 'MyBaseC'.

Reply | Email | Modify 
Why to use sealed keyword by Benjamin On February 1, 2010
Great job!
However I may disagree with the argumentation of using sealed classes to host static only content. There is a static kyoword on a class for this purposes. This post contains some good motivations on this issue http://geekswithblogs.net/gmamaladze/Default.aspx 

Reply | Email | Modify 
Static classes was introduced later by Mahesh On February 2, 2010
Yes agree. However, when I wrote this article, at that time, C# (.NET) did not have static classes. Static classes were later introduced in C#.
Reply | Email | Modify 
Re: Can we declare a method as sealed in csharp? by Satyapriya On August 29, 2010
Dear sir,
Can we declare a method as sealed in Csharp?
Reply | Email | Modify 
Re: Re: Can we declare a method as sealed in csharp? by Mahesh On August 31, 2010
I am not sure. Why would you want that?
Reply | Email | Modify 
Re: Re: Re: Can we declare a method as sealed in csharp? by Akhil On September 3, 2010

In C# a method can't be declared as sealed.However when we override a method in a derived class, we can declare an overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

using System;

class Class1
{
public int x;
public int y;

public virtual void Method()
{
Console.WriteLine("virtual method");
}
}

class Class2 : Class1
{
public override sealed void Method()
{
Console.WriteLine("sealed method");
}
}

class MainClass
{
public static void Main()
{
Class1 c1 = new Class2();
c1.x = 110;
c1.y = 150;
Console.WriteLine("x = {0}, y = {1}", c1.x, c1.y);
c1.Method();
}
}

Reply | Email | Modify 
Can a sealed class have a virtual method by renu On October 14, 2010
Can a sealed class have a virtual method
Reply | Email | Modify 
Re: Can a sealed class have a virtual method by Mahesh On November 7, 2010
What are you trying to do? Purpose of sealed and virtual is totally different.
Reply | Email | Modify 
About Sealed Class by Govindaraj On April 18, 2011
This is wonderfull exampled for sealed class
Reply | Email | Modify 
HI by jhn On April 25, 2011
need more expl dude !!!
Reply | Email | Modify 
Queries with sealed class by Prashant On December 29, 2011
How is it going to be advantage while making a class as sealed if it has all the members as static Could you please throw some light on this.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.