65.9K
CodeProject is changing. Read more.
Home

Tip: Dynamic 'Enum' like solution

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 15, 2011

CPOL
viewsIcon

38635

Dynamic 'Enum' like solution.

This is very useful if you wish to be able to create dynamic enums.

Requirements

  • You need to enumerate something, but wish to add items to it in runtime (e.g., your server should support v1 protocol and v2 protocol where v2 protocol extends v1.enum).
  • You wish to extend this enum dynamically by an outside add-in.

Solution

enum MyEnum : ulong
{
    // NOTICE: string_name = ulong_value,
    first = 2<<0,
    second = 2<<1,
    last = 2<<2,

    max = 2 << 63
    // dynamic string name = dynamic ulong value!
}

Dictionary<string, ulong> DynamicEnum1 = new Dictionary<string, ulong>()
{
    {"first", 2 << 0},
    {"second", 2 << 1},
    {"last", 2 << 2},

    {"max", 2 << 63}
};

public void usage()
{
    MyEnum qwe = MyEnum.first;

    UInt64 qwe2 = DynamicEnum1["first"];
    DynamicEnum1.Add("add_another_one", 2 << 3);

    // (UInt64)qwe == qwe2!!
}

Hope it helps.

Original article - http://shloemi.blogspot.com/2011/11/tip-c-dynamic-enum-like-solution.html[^].