Monday, October 18, 2004

Converting an Enum to its value...

Back in the presenters' room at Code Camp 2 I had an interesting conversation with Dave Mitchell of connectedbits.

He was creating a serialization library and having some trouble converting System.Enum to its underlying value. Sounds strange but you can't just cast it.

He has a method that wants to trat enums generically independent of the particular type of enum.


class Serializer
{
void Write(Enum enumValue)
{
}
}

He calls it with something like
serializer.Write(Color.Blue);
The code :
int val = (int)enumValue;
Does not compile.

The solution he is living with is:
int val =(int)Enum.Parse(enumValue.GetType(),enumValue.ToString());

I think I found him a better solution.

int GetEnumValue(Enum enumValue)
{
return (int)Convert.ChangeType(enumValue,val.GetTypeCode());
// Or
//return (int)Convert.ChangeType(enumValue,typeof(int));
}


But this ignores the fact that an enum can be a byte, sbyte, short, ushort, int, uint, long, or ulong.

So a more complete implementation might look something like this:

void Write(Enum enumValue)
{
TypeCode code = val.GetTypeCode();
object valueAsObject = Convert.ChangeType(enumValue, code);
switch(code)
{
case TypeCode.Byte :
Write((byte)valueAsObject);
break;
case TypeCode.SByte :
Write((sbyte)valueAsObject);
break;
case TypeCode.Int16 :
Write((short)valueAsObject);
break;
case TypeCode.UInt16 :
Write((ushort)valueAsObject);
break;
case TypeCode.Int32 :
Write((int)valueAsObject);
break;
case TypeCode.UInt32 :
Write((uint)valueAsObject);
break;
case TypeCode.Int64 :
Write((long)valueAsObject);
break;
case TypeCode.UInt64 :
Write((ulong)valueAsObject);
break;
}


Now we just supply overloaded Writes for each type and can write the correct underlying value.

0 Comments:

Post a Comment

<< Home