c# Enums

etienne_marais

Honorary Master
Joined
Mar 16, 2008
Messages
16,250
Reaction score
19,740
Location
Centurion
I thought this would be relatively trivial, but my only solution so far is a bit convoluted:

// values come from database
public enum MyEnumRaw : byte
{
Uknown = 0,
Value1 = 1,
Value2 = 2,
Value3 = 3
}

// multiple Enum values from MyEnumRaw must map to a bitmap value for 'combined' storage elsewhere in DB
public enum MyEnumBitmap : Int32
{
Unknown = 1,
Value1 = 2,
Value2 = 4,
Value3 = 8
}

Thus when data is read from the DB, and I get the values 3,0 and 1

From EnumRaw that would be Value3, Unknown and Value1

From MyEnumBitmap these three values will map 'back' to 8, 1 and 2

8, 1 and 2 must be summed together, thus 8+1+2=11 to be stored in a bitmap vector.

I am not currently interested in alternatives such as Dictionaries or other lookup mechanisms, is the following the correct / most elegant handling of enumeration mapping for this scenario ?

int valueFromDB = 8;
(Int)(MyEnumBitmap)Enum.Parse(typeof(MyEnumBitmap ),((MyEnumRaw )valueFromDB).ToString())



I initially thought I would be able to do something more or less to the following extent (though obviously flawed):

(Int)(MyEnumBitmap)(MyEnum)valueFromDB
 
Last edited:
An enum extension method should suffice.

PHP:
 static class EnumExtensionMethod
  {
    public static MyEnumBitmap ToMyEnumBitmap(this MyEnumRaw value)
    {
      switch (value) {
        case MyEnumRaw.Uknown:
          return MyEnumBitmap.Unknown;
        case MyEnumRaw.Value1:
          return MyEnumBitmap.Value1;
        case MyEnumRaw.Value2:
          return MyEnumBitmap.Value2;
        case MyEnumRaw.Value3:
          return MyEnumBitmap.Value3;
        default:
          return MyEnumBitmap.Unknown;
      }
    }
  }
 
Top
Sign up to the MyBroadband newsletter
X