enums in csharp
Basic Enum
- is a value type
- let you define a group of named intergral numeric constants
- add functionality to enum type using extension methods
- always consider defining an enumeration member whose value is 0, because the memory used for the enumeration is initialized to zero by default when it's created.
using System;
using System.Linq;
// Season Enum, underlyingType is Int32, values is 0,1,2,3
Describe<Season>();
// ErrorCode Enum, underlyingType is UInt16, values is 0,1,100,200
Describe<ErrorCode>();
void Describe<TEnum>() where TEnum : Enum
{
var underlyingType = Enum.GetUnderlyingType(typeof(TEnum));
var values = (
from object value in Enum.GetValues(typeof(TEnum))
select Convert.ChangeType(value, underlyingType)
).ToList();
var description = $"{typeof(TEnum).Name} Enum, " +
$"underlyingType is {underlyingType.Name}, " +
$"values is {string.Join(',', values)}";
Console.WriteLine(description);
}
// default underlying value type is **int**
// automatically assigned 0,1,2...
enum Season
{
Spring,
Summer,
Autumn,
Winter
}
// explicitly specify the underlying value type and its value
enum ErrorCode : ushort
{
None = 0,
Unknown = 1,
ConnectionLost = 100,
OutlierReading = 200
}
Flags Enum
- bit flags, means that use a bit field to stand for a value, so often used with bitwise logical operators(AND, OR, EXCLUSIVE OR)
- define values be power of two to avoid overlap
- Use None as the name of the flag enumerated constant whose value is 0.
[Flags]
using System;
// 0001 - Red
// 0010 - Green
// 0011 - Red, Green
// 0100 - Yellow
// 0101 - Red, Yellow
// 0110 - Green, Yellow
// 0111 - Red, Green, Yellow
// 1000 - Blue
// 1001 - Red, Blue
// 1010 - Green, Blue
// 1011 - Red, Green, Blue
// 1100 - Yellow, Blue
// 1101 - Red, Yellow, Blue
// 1110 - Green, Yellow, Blue
// 1111 - Red, Green, Yellow, Blue
for (var color = 1; color < 1 << 4; color++)
{
Console.WriteLine(
"{0,4} - {1:G}",
Convert.ToString(color, 2).PadLeft(4, '0'),
(PrimaryColors)color
);
}
[Flags]
enum PrimaryColors : ushort
{
None = 0, // 0000 - 0
Red = 1 << 0, // 0001 - 1
Green = 1 << 1, // 0010 - 2
Yellow = 1 << 2, // 0100 - 4
Blue = 1 << 3 // 1000 - 8
}
We can understand the above example like this, Red = 1 << 0, // 0001 - 1 means that for a given value, if the last bit is 1, we say the value contains the "Red flag", otherwise not contains.
System.Enum
- the base class for enumerations
- can be used as a base class constraint (enum constraint) to specify that a type parameter is an enumeration type
- has many useful static method, such as
GetNames, GetValues, IsDefined, Parse...
Reference
- C# 9.0 in a Nutshell, Chapter 3 Enums Section
- Enumeration types - C# reference
- FlagsAttribute Class
- Enum Class (System)

浙公网安备 33010602011771号