Monday, November 14, 2011

Tip: C# dynamic 'Enum' like solution.

Hi,
This is very usefull if you wish to be able to create dynamic enums.

Motivation
* 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 extand this enum dynamically by an outside addin.

Solution and prof



Code Snippet
  1. enum MyEnum : ulong
  2. {
  3.     // NOTICE: string_name = ulong_value,
  4.     first = 2<<0,
  5.     second = 2<<1,
  6.     last = 2<<2,
  7.  
  8.     max = 2 << 63
  9.     // dynamic string name = dynamic ulong value!
  10. }
  11.  
  12. Dictionary<string, ulong> DynamicEnum1 = new Dictionary<string, ulong>()
  13. {
  14.     {"first", 2 << 0},
  15.     {"second", 2 << 1},
  16.     {"last", 2 << 2},
  17.  
  18.     {"max", 2 << 63}
  19. };
  20.  
  21. public void usage()
  22. {
  23.     MyEnum qwe = MyEnum.first;
  24.  
  25.     DynamicEnum1.Add("another_one", 2 << 3);
  26.     UInt64 qwe2 = DynamicEnum1["first"];
  27.  
  28.     // (UInt64)qwe == qwe2!!
  29. }


Hope it helps.

5 comments:

  1. Found this solution using reflection (much more complicated with the same results):
    http://www.codeproject.com/KB/cs/SetEnumWithReflection.aspx

    ReplyDelete
  2. Here is a full example usage:
    http://shloemi.blogspot.com/2011/11/example-c-dynamic-enum-like-solution.html

    ReplyDelete
  3. BTW - If you need this solution it indicates that you have a bug in the design. Use it only to 'Lower the fire' and when you have time (which usually dons't happen :), try to find a better solution.
    And... good luck.

    ReplyDelete
  4. You can take it to the next level and add a constructor that recieves an enum, populates the dictionary with it's value and name, and add new values ass needed, this way you can still use your old enum.

    ReplyDelete