tags:

views:

479

answers:

2

If i declare

[Flags]
public enum MyColor
{
    Red = 1;
    Green = 2;
    Blue = 4;
    White = 8;
    Magenta = 16;
    ... (etc)
}

Is there a way to determine/set the number of Bytes that this enum takes up? Also, what byte order would it end up in? (e.g. do i have to do a HostToNetwork() to properly send it over the wire?) Also, in order to call HostToNetwork, can i cast as a byte array and iterate?

+7  A: 
[Flags]
public enum MyColor : byte // sets the underlying type.
{
    Red = 0;
    Green = 1;
    Blue = 2;
    White = 4;
    Magenta = 8;
    ... (etc)
}

It's not possible to directly set the endianness. You can use some well-crafted numbers that simulate big-endian bytes on a little endian system. However, I'd always use explicit APIs for converting byte orders.

Mehrdad Afshari
For reference the default size if not specified is Int32, and being standard numbers under the hood have all the same rules as a number when it comes to byte order.
KeeperOfTheSoul
A: 

Complete answer is:

  • Is there a way to determine/set the number of Bytes that this enum takes up?

Yes:

[Flags]
public enum MyColor : byte // sets the underlying type.
{
    Red = 1;
    Green = 2;
    Blue = 4;
    White = 8;
    Magenta = 16;
    ... (etc)
}
  • Also, what byte order would it end up in?

Whatever it's compiled in, so for my case, x86 (little).

  • Also, in order to call HostToNetwork, can i cast as a byte array and iterate?

This is where it's tricky. I found out a few things:

Andy
Also, you can *get* the underlying type with `Enum.GetUnderlyingType(typeof(MyColor))`: http://msdn.microsoft.com/en-us/library/system.enum.getunderlyingtype.aspx
280Z28