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
- 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;
- DynamicEnum1.Add("another_one", 2 << 3);
- UInt64 qwe2 = DynamicEnum1["first"];
- // (UInt64)qwe == qwe2!!
- }
Hope it helps.
Found this solution using reflection (much more complicated with the same results):
ReplyDeletehttp://www.codeproject.com/KB/cs/SetEnumWithReflection.aspx
Here is a full example usage:
ReplyDeletehttp://shloemi.blogspot.com/2011/11/example-c-dynamic-enum-like-solution.html
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.
ReplyDeleteAnd... good luck.
Tracking... Also posted here:
ReplyDeletecodeproject
stackoverflow
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