Forums - C# Corner

Forum guidelines

Difference between static and sealed classes in C#

Jun 28 2011 12:15 PM
Static class:
1) A static class can not be instantiated. Means you can't create instance of          any static class.
2) A static class can have only static member (e.g static method, property, and         variables).
3) A static class restrict the user to call default constructor of the class.
4)
Static classes can only have static constructor to initialize static members.
5) Static classes are sealed so they can not be inherited.

Sealed Class:
1) When a class defined as sealed its not possible to inherit.
2)  A Sealed class is last class of Inheritance feature.
3) 
Use the sealed modifier in a class declaration to prevent inheritance of the         class.
4) It is not permitted to use the abstract modifier with a sealed class.
5) Structs are implicitly sealed; therefore, they cannot be inherited.
Example:
// cs_sealed_keyword.cs // Sealed classes 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);     } }
Output:
x = 110, y = 150
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'.


Answers (9)

C# Corner Hyderabad Developer Conference

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.