Type declaration is an implicit static member

Someone I know just asked me to explain this statement from MSDN , and I was stunned.

Declaring a constant or type is implicitly a static member.

This phrase "or type declaration is an implicit static member" just doesn't make sense to me.

What does it mean?

+6
source share
5 answers

It seems to me that a type declaration is implicitly a static member .
Because if you have a class:

 class Foo { public class Bar { } } 

You cannot access the Bar class with:

 Foo f = new Foo(); Bar b =new f.Bar(); 

(I'm not even sure how to write it to make sense).
If you want to access the Bar class, you will need to do the following:

 Bar b = new Foo.Bar() 

You access it through a class, not an instance. facility
Therefore, Bar is a static member of Foo .

+4
source

In the context of this article, I believe that they define types simply to define internal struct s, inner- class es, and enum - which can always be referenced in a static context as a type.

+2
source

This means that when you define such a class,

  public class Message { const int i = 10; enum NewType{ typeval, typevale2 } } 

Here both are implicitly static members.

+2
source

The constant is implicitly static, but it differs from a simple static field in that it cannot change during the execution of your program. He is still motionless though ..

0
source

type declaration

A type declaration is a class declaration (section 10.1), a structure declaration (section 11.1), an interface declaration (section 13.1), an enumeration declaration (section 14.1), or a delegate declaration (section Section 15.1).

from MSDN Dossier Type Announcements

static elements

When a declaration of a field, method, property, event, operator, or constructor contains a static modifier, it declares a static member. In addition, declaring a constant or type implicitly declares a static member. Static elements have the following characteristics:

  • When a static member M refers to member access (section 7.5.4) of the EM form, E must denote a type containing M. This is a compile-time error for E to denote an instance.
  • A static field identifies exactly one storage location. No matter how many instances of the class are created, there is only one copy of the static field.
  • A static member of a function (method, property, event, operator or constructor) does not work on a specific instance, and it is a compile-time error to refer to this in such a member of the function.

from Static Elements and Instances of the MSDN Dossier

Thus, this means Constants , and all Type declaration types are static without adding the static .

0
source

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


All Articles