Enum C#
Enum C#
What is Enumeration?
Every Enum type has an underlying type which can be any integral type except char.
The default underlying type is int.
The first enumerator has the value 0 by default and the value of each successive
enumerator is increased by 1
1 enum colors
2 {
3 Red = 1,
4 Blue = 2,
5 Yellow = 3,
6 Green = 4
7 };
Enum Operators:
The operators that work with enums are:= == != < > <= >= + ^ & | ~ += -= ++ sizeof
The bitwise, arithmetic, and comparison operators return the result of processing the
underlying integral values.
Addition is permitted between an enum and an integral type, but not between two enums.
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
[Flags]
enum BookGenres
{
None = 0,
ScienceFiction = 0x01,
Crime = 0x02,
Romance = 0x04,
History = 0x08,
Science = 0x10,
Mystery = 0x20,
Fantasy = 0x40,
Vampire = 0x80,
};
You can use the BookGenres enumeration in bit-field operations. To see what [Flags]does,
examine the following code and its output:
Output:
Binding: Hardcover
Double Binding: 3
Genres: Romance, Fantasy, Vampire
Note that the enumeration with the [Flags] attribute printed out each genre correctly.
However, .NET 4 introduces the HasFlag() method, which accomplishes the same thing:
Enum.GetName() returns the same string you would get if you just called ToString()on a
value.
You can also use Enum.GetNames() to get all the strings back directly
Example:
If your enumerations must match external values, then explicitly assign a value to
each enumeration member.
Always use [Flags] when you need to combine multiple values into a single field.
Flag enumerations must have values explicitly assigned that are unique powers of
two (1, 2, 4, 8, 16, and so on) to work correctly.
An enumeration should have a singular name if it is not used as flags, whereas flags
should have plural names.