Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing non-static enum values from static methods

Tags:

c#

public enum sEnum
{
    zero = 0, one = 1
}

public int x;

public static void a(sEnum s)
{
    x = 3;
    if (s == sEnum.one) ...
}

Why can values of the enum be checked here, as the static keyword isn't used? Where is this documented in the language specification?

like image 253
seamast Avatar asked Jan 21 '23 11:01

seamast


2 Answers

Enums are just named values so you can use them in a static context just like any other constant.

Section 3.4.3 of the language specification states:

The members of an enumeration are the constants declared in the enumeration

like image 63
Brian Rasmussen Avatar answered Jan 24 '23 01:01

Brian Rasmussen


I think 14.3 in the specs is what you are looking for:

Enum members are named and scoped in a manner exactly analogous to fields within classes. The scope of an enum member is the body of its containing enum type. Within that scope, enum members can be referred to by their simple name. From all other code, the name of an enum member must be qualified with the name of its enum type. Enum members do not have any declared accessibility—an enum member is accessible if its containing enum type is accessible.

like image 41
asawyer Avatar answered Jan 24 '23 01:01

asawyer