Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and Sealed class differences

This may help you:

+--------------+---+-------------------------+------------------+---------------------+
|  Class Type  |   | Can inherit from others | Can be inherited | Can be instantiated | 
|--------------|---|-------------------------+------------------+---------------------+
| normal       | : |          YES            |        YES       |         YES         |
| abstract     | : |          YES            |        YES       |         NO          |
| sealed       | : |          YES            |        NO        |         YES         |
| static       | : |          NO             |        NO        |         NO          |
+--------------+---+-------------------------+------------------+---------------------+

In simple words

Static Class

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Sealed Class

A sealed class cannot be used as a base class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.


You can let a sealed class inherit from another class, but you cannot inherit from a sealed class:

sealed class MySealedClass : BaseClass // is ok
class MyOtherClass : MySealedClass     // won't compile

A static class cannot inherit from other classes.


You can simply differentiate both of them as:

       Sealed Class       |        Static Class
--------------------------|-------------------------
it can inherit From other | it cannot inherit From other
classes but cannot be     | classes as well as cannot be
inherited                 | inherited

Simple answer is a sealed class cannot be used as a base class.

I'm trying to show you sealed class is a derived class in the below code

 public sealed class SealedClass : ClassBase
{
    public override void Print()
    {
        base.Print();
    }
}

and another sealed feature is only accessible with instance from it.(you can not inherit from it)

 class Program
{
    static void Main(string[] args)
    {
        SealedClass objSeald = new SealedClass();
        objSeald.Name = "Blah blah balh";
        objSeald.Print();

    }
}