|
Enumerators in C# |
|
|
|
Following is an example illustrating an enum: class Class1 static void Main ( string [ ] args ) Console.WriteLine ( color.red ) ; } } enum color red, blue, green } Output: red We can also change the underlying data type (which is int by default) as in the following snippet: public class Class1 static void Main ( string [ ] args ) Console.WriteLine ( color.red ) ; } } enum color:byte red = 8, blue, green } Output :- red But here we have to be careful that we should not use a value, which is out of range, for example assigning a value like 500 to red in this program will result in error. To check the value of blue we write Console.WriteLine ( (int) color.blue ) ; And we get 9. This is because every next member value increments by one. Internally enum is a sealed class, and it cannot even inherit from a sealed class. An enum cannot have two members with the same name and the following code class Class1 static void Main ( string [ ] args ) Console.WriteLine ( (int) color.blue ) ; } } enum color red, blue, green, red } flashes an error: class enum1.color already consists a definition for ‘red’.
Here’s a program illustrating how to print out values of an enum.
class Class1 { static void Main ( string [ ] args ) string [ ] names ; Console.WriteLine ( i ) ; } } } enum color red, blue, green, yellow, brown } And the output is: We created an array of strings called names. The GetNames( ) function returns all the names of the specified enum. We pass the typeof the enum to this function. Then using the foreach statement we print these names out.
Here’s a program illustrating how to compare two values of an enum.
class Class1 static void Main ( string [ ] args ) Console.WriteLine ( color.green.CompareTo ( color.red ) ) ; } } enum color red, blue, green, yellow, brown } Here the value of green is greater than red so the output is 1 and value of red is less than yellow which results in a –1. |