Loading

enums in csharp

Basic Enum

  1. is a value type
  2. let you define a group of named intergral numeric constants
  3. add functionality to enum type using extension methods
  4. 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

  1. bit flags, means that use a bit field to stand for a value, so often used with bitwise logical operators(AND, OR, EXCLUSIVE OR)
  2. define values be power of two to avoid overlap
  3. 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

  1. the base class for enumerations
  2. can be used as a base class constraint (enum constraint) to specify that a type parameter is an enumeration type
  3. has many useful static method, such as GetNames, GetValues, IsDefined, Parse...

Reference

posted @ 2021-10-19 00:32  deleteLater  阅读(71)  评论(0)    收藏  举报