Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Tip: Dynamic 'Enum' like solution

0.00/5 (No votes)
20 Nov 2011 1  
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


C#
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[^].

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here