Click here to Skip to main content
15,886,067 members
Articles / Enum
Tip/Trick

Tip: Dynamic 'Enum' like solution

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Nov 2011CPOL 37.1K   2   7
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Israel Israel
Programming ( self taught ) since about 1987 when I sneaked lessons to the Apple ][ lab Smile | :) .

Comments and Discussions

 
GeneralI dont get it. A dictionary has been used. Where is the enum... Pin
Abhinav S8-Jan-12 3:32
Abhinav S8-Jan-12 3:32 
GeneralRe: Hellow Abhinav,The subject of this tip is to find an altern... Pin
ShlomiO8-Jan-12 22:03
ShlomiO8-Jan-12 22:03 
GeneralWhat's the point? All you've done is show how to use a Dicti... Pin
lewax0016-Nov-11 10:15
lewax0016-Nov-11 10:15 
GeneralRe: :), you'r right, my bad - fixed it, 10x. Pin
ShlomiO19-Nov-11 6:39
ShlomiO19-Nov-11 6:39 
GeneralIn my opinion when ever I find that the solution to a proble... Pin
Reiss15-Nov-11 4:53
professionalReiss15-Nov-11 4:53 
GeneralRe: First - I agree, there is a problem in the design if you nee... Pin
ShlomiO15-Nov-11 22:42
ShlomiO15-Nov-11 22:42 
QuestionTake it to the next level... Pin
ShlomiO8-Jan-12 0:13
ShlomiO8-Jan-12 0:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.