How is a static class implicitly abstract?

John Skeet in his C # in Depth book talks about a static class:

It cannot be declared abstract or sealed, although it is implicitly both of them.

An abstract class is designed for a base class for derived types. We can only instantiate an abstract class by instantiating one of its derived types. On the other hand, we cannot extract anything from a sealed class. A sealed, abstract class would be worthless in many ways. What does Skeet mean under a static class that is abstract and sealed? Is he just talking about the inability to create it directly?

+5
source share
4 answers

What does Skeet mean if the static class is abstract and sealed?

I mean, submission in IL.

For instance:

static class Foo {} 

Generates IL:

 .class public abstract auto ansi sealed beforefieldinit Foo extends [mscorlib]System.Object { } // end of class Foo 

Thus, even a language that does not know about static classes will not allow you to extract another class from it and will not allow you to create it.

Also, as the C # specification refers to it:

A static class cannot include a private or abstract modifier. Note, however, that since a static class cannot be created or derived from it, it behaves as if it were both sealed and abstract.

+18
source

CIL has no static classes. CIL has abstract classes and has sealed classes. An abstract class cannot be created directly (although a concrete class can be obtained from an abstract class). Sealed class could not be obtained. Combine them, and you have something that the C # compiler can use to implement static classes.

By the way, this fact that CIL does not have static classes means that restrictions on static classes as arguments of a general type also do not exist in CIL. Given static class X , CIL allows you to create what C # will call List<X> . However, given that there can be no instances of X or any class derived from it, the only value you can store in such a list is null .

+5
source

This is implicitly abstract because you cannot create an instance of the class.

It is implicitly sealed because you cannot extract from it.

+1
source

This means that it is implicitly abstract because the class cannot be created. It is implicitly sealed because you cannot extend or inherit it.

+1
source

Source: https://habr.com/ru/post/1213646/


All Articles