ECMA-334 C# Language Specification17.2.5: Static and instance members |
Members of a class are either static members or instance members.
When a field, method, property, event, operator, or constructor declaration includes a static modifier, it declares a static member. In addition, a constant or type declaration implicitly declares a static member. Static members have the following characteristics:
member-access
(14.5.4) of the form E.M, E must denote a type that has a member M. It is a compile-time error for E to denote an instance. When a field, method, property, event, indexer, constructor, or destructor declaration does not include a static modifier, it declares an instance member. (An instance member is sometimes called a non-static member.) Instance members have the following characteristics:
member-access
(14.5.4) of the form E.M, E must denote an instance of a type that has a member M. It is a compile-time error for E to denote a type.
class Test
{
int x;
static int y;
void F() {
x = 1; // Ok, same as this.x = 1
y = 1; // Ok, same as Test.y = 1
}
static void G() {
x = 1; // Error, cannot access this.x
y = 1; // Ok, same as Test.y = 1
}
static void Main() {
Test t = new Test();
t.x = 1; // Ok
t.y = 1; // Error, cannot access static member through
instance
Test.x = 1; // Error, cannot access instance member through type
Test.y = 1; // Ok
}
}
simple-name
(14.5.2) can be used to access both instance members and static members. The G method shows that in a static function member, it is a compile-time error to access an instance member through a simple-name
. The Main method shows that in a member-access
(14.5.4), instance members must be accessed through instances, and static members must be accessed through types. end example]