C# Enum and Static Enum Methods

C# Enum (Enumerations):

C# Enum(Enumerations) are types of values ​​that are defined by the programmer by listing their values. Typical examples are enumerations for days of the week, seasons, rounding modes, color palettes and so on.


Definition of C# Enum(Enumeration):

C# Enum types are declared with the keyword enum. The name is followed by the keyword the new Enum and finally, enclosed in curly brackets and separated by commas and DayOfWeek Enum, as it is also defined in the System namespace

The individual C# Enum values ​​are mapped internally to int constants. The first value of the The 0 is assigned to the Enum, all subsequent values ​​are assigned the one increased by 1 Numerical value assigned to their predecessor. You can control the mapping of the c# Enum values ​​yourself by adding individual or all values ​​in explicitly assign numbers to the definition. The following definition creates e.g. an c# Enum in which the Days of the week can be mapped to the numbers from 1 (Monday) to 7 (Sunday).

The c# Enum values ​​can only be mapped to whole numbers, but these must not necessarily of type int. If you use any other integer type (except char) enter this after the name of the c# Enum:



C# Enum Use:

define variables of c# Enums  in the normal way by specifying the type and the variable name:

You can assign the values ​​of the enumeration to the variables of an Enum:

The assignment of integer values ​​is only possible through explicit type conversion. Same goes for that Assignment of Enum values ​​to integer variables:

Note: There is no value range check for c# Enums . If you add an c# Enumeration variable using explicit Assigning a type conversion a numeric value for which no value is defined in the Enum does not result in a Error message!

Leaving aside the fact that there are no implicit casts between enums and Integern does not give up any arithmetic operations except for incrementing and decrementing If c# Enums  are allowed, you can work with c# Enums  in much the same way as with integers. Especially you can use values ​​or variables from enums

  • increment and decrement
  • to compare
  • manipulate bit by bit
  • use as a condition for switch statements.

C# Enum and switch:

C# Enum types are great for implementing switch statement. The following program demonstrates this using the DayOfWeek Enum defined in the system (as discussed above). The program first creates a DateTime object for the current day. As an object of the DateTime class it has a DayOfWeek property that returns the day of the week of the date represented  and as the value of the c# Enum System.DayOfWeek. The switch branch of the program compares the Property with the individual values ​​of the Enum.


Example: how to use c# Enum with switch statement:

Output:

C# Enum



System.Enum class:

In C # Enums are based on the abstract base class System.Enum. In addition to the ones inherited from Object Methods Enum also defines a CompareTo() method for comparing.

Static enum methods:

Methods Description
string Format(Type enumType, Object value,

string format)

Formats an c# Enum value into a string. As arguments pass in the type of Enum, the value to be formatted and one of the following format specifications:

“G”, “g”:  Output of the name (like calling ToString ())

“X”, “x”:  Output of the assigned integer value as Hexadecimal number

“D”, “d”: Output of the assigned integer value

“F”, “f”: like “G”, “g”

string GetName(Type enumType, Object value) Returns the name of an c# Enumeration value. You pass the type and a variable of the Enum as arguments.
string[] GetNames(Type enumType) Returns a string array with the Returns the names of the Enum values.
Type GetUnderLyingType(Type enumType) Returns the type of the assigned number constants. (You can specify the c# enumeration type of an enumeration variable like Query with the instance method GetType() as usual.)
Array GetValues ​​(Type enumType) Returns an array with the number constants for the transferred Enum type the enumeration values.
bool IsDefined(Type enumType, Object value) Checks whether there is an enumType for the passed value in the enumeration Member there.
Object Parse(Type enumType, string value, bool ignoreCase) Converts a string containing the name of an enumeration value to same around. The third parameter is optional and determines whether the upper / lower case should be ignored.

The following code fragment uses the static Enum methods GetNames() and GetValues​​() to return the Values ​​and assigned number constants of the System.DayOfWeek Enum.


Example: how to use static enum class getName and getValue in c# programming:

Output:

C# Enum

C# enum type

An c# enum type variable can take one of the values ​​listed in the Enum (here the enumeration CivilState which includes four values):

The first line (c# enum definition) must be placed in the class but outside a function. The c# enum definition can be terminated with a semicolon, but it is not required. The variable cs can be a variable local to Main (in general, local to a function) or a class field. The variable cs can contain one of the values ​​specified in the definition of Enum.


Later, we will see that a variable of a somewhat different enum type (because of the attribute Flags) can contain zero, one (default) or more of the values ​​listed in the c# Enum. Although this should be considered as internal cooking to the compiler, the latter associates the value 0 to Single, the value 1 to Married and so on, which allows you to write (an int casting must be done because the values ​​of an c# enumeration are not always encoded in the int format):

but it is highly preferable to write (imagine removing one of the values ​​or modifying the order of the possible values ​​in the c# Enum):

So consider that Single, for example, is one of the possible states of the State Enum Civilian and that Single is Single, regardless of the value assigned to Single by the compiler.

An ” C# enumeration” type variable can be incremented or decremented (the second line is acceptable to move on to the next state but the third is frankly dubious from a point of view methodological):

Nothing prevents copying an erroneous value into cs (no error is reported during compilation or in progress):

but problems are likely to arise later. By default, the various values ​​associated with an c# Enum are encoded in the int format. But you can choose another representation, for example byte to occupy less space memory with CivilState variables:

It is also possible to associate very specific values ​​with each value of the c# Enum (by default, 0 for the first value and increment by 1 for each following value):



However, it is prudent to provide a zero value for the most common of the values ​​because the constructors Objects, by default, initialize the memory allocated to c# Enum type fields to zero. Enumerated type variables can be considered as objects of the Enum class. The variables of type enum are nevertheless of type value and are therefore allocated only on the stack. The methods of this Enum class that may be of interest  To convert a string of characters to one of the possible values ​​of the c# enumeration, we write:

cs now contains the WidowedCivilState value. If the third argument had been true, the second could have been WIDOWER or WIdower (no distinction is made between upper and lower case). In case of error (case where the second argument does not correspond to any of the possible values ​​of c# Enum), the ArgumentException exception is thrown

To display the different possible values ​​of the Enum (Single, Widower, etc.), we write:

The ToString method, applied to an object of type Enum, displays the name of the value. Through example:

copies the string Married to s.


C# Enum Binary indicators:

In the previous examples, an enumeration type variable could not contain, at a time given, only one value of the Enum. An c# Enum(enumeration) can relate to binary indicators (bit fields in English), which makes it possible to set multiple flags (a file, for example, can be both hidden and read-only) independently of each other. This is particularly the case with the FileAttributes enumeration. To create an Enum made up of binary indicators, we write (B1 corresponds to the position of the far right bit, B2 to the one immediately to its left and so on):

The values ​​associated with the different elements must be specified. They must be powers of of them. These values ​​have been expressed in hexadecimal here, but they are not required. We create and initialize a variable of our Indicators type by (| is the OR operator at the level binary, it suffices for one of the two bits to be 1 for the result to also be 1):

i contains the indicators B1 and B3: Indicators.B1, in binary, is 0001, Indicators.B3 is 0100 and the result i is 0101. To test if an indicator is set, we write (here test for the presence of B2):


B2 is set to one in i if i & Indicators. B2 is well different from zero. & is the operator AND at binary level: both bits must be at 1 so that the result is also at 1. To test if two indicators are positioned, we must write (do not forget that> has priority by relation to &, which makes the parentheses mandatory):

i.ToString () in this case returns B1, B3. The methods of the C# Enum class apply to binary flags. We can thus write:

An exception is obviously thrown if s contains anything other than valid flags.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: