Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare static classes as sealed and abstract in C#?

Tags:

c#

This MSDN article states that static classes should be declared as sealed and abstract. I was under the impression that static classes were already sealed. Why would you also need to declare a static class as sealed?

like image 751
Guy Avatar asked Aug 12 '09 22:08

Guy


People also ask

Why static classes are sealed?

As static class is sealed, so no class can inherit from a static class. We cannot create instance of static class that's the reason we cannot have instance members in static class, as static means shared so one copy of the class is shared to all. Static class also cannot inherit from other classes.

Can we define abstract or static class as sealed?

static class cannot be marked sealed because it is made sealed by compiler by default. Static classes are sealed and therefore cannot be inherited. static class cannot be marked as abstract , because it would be pointless.

Can a static class be sealed?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

What is the difference between sealed class and static class?

Static classes are loaded automatically by the . NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. A sealed class cannot be used as a base class. Sealed classes are primarily used to prevent derivation.


2 Answers

I think the pertinent bit from that article is:

"Do declare static classes as sealed and abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes."

Remember, the .NET framework supports a lot of different languages.

like image 125
Dan Diplo Avatar answered Sep 18 '22 16:09

Dan Diplo


C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]

C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.

like image 36
SolutionYogi Avatar answered Sep 19 '22 16:09

SolutionYogi