Search code examples
c#enumscastingcompact-frameworkienumerable

Cast Enum to IEnumerable byte


Given the following Enum

enum MyEnum {
   MyVal1 = 0x0000,
   MyVal2 = 0xF0F0,
   MyVal3 = 0x1234
}

I want to write a method returning an IEnumerable for a given Enum.

IEnumerable<byte> Foo(MyEnum myEnum){
     //...
}

So that

byte[] bytes = Foo(MyEnum.MyVal1).ToArray(); //bytes == 0x0000
byte[] bytes = Foo(MyEnum.MyVal2).ToArray(); //bytes == 0xF0F0
byte[] bytes = Foo(MyEnum.MyVal3).ToArray(); //bytes == 0x1234

Please advice. I'm on Compact Framework 3.5


Solution

  • Actually, you could use built-in BitConverter.GetBytes for that purpose:

    IEnumerable<byte> Foo(MyEnum myEnum) {          
        return BitConverter.GetBytes((ushort)myEnum);           
    }
    

    Probably the only key you want to note here is to cast your enum to, in this case, ushort, since your enum is 2 bytes.

    Also, note that the result will be by default following BitConverter.IsLittleEndian property. If it is true, then the result is little endian and if it is false the result is big endian.