Can I cast to a [Flags] enum?

D

Dwight.Dexter

I have an enum variable. Is there some way to cast an int or BitArray
and get my enum value? I have to communicate with an old C-style
sever so I get an array of bits("0","1"). But I'm using an enum
variable to store the data.

[Flags]
public enum LaneCapabilities
{
MLT = 0,
ACM = 1,
AVI = 2,
ATIM = 4,
Degraded = 8,
CCS = 16
}

Ended up with this code:

string[] flags = ReadRTMessage().Split(' ');

LaneCapabilities capable = new LaneCapabilities();
for( int i = 0; i<flags.Length; i++)
{
switch(i)
{
case 0 :
if (flags[0] == "1")
capable |= LaneCapabilities.ACM;
break;
case 1 :
if (flags[1] == "1")
capable |= LaneCapabilities.ATIM;
break;
case 2:
if (flags[2] == "1")
capable |= LaneCapabilities.AVI;
break;
case 3:
if (flags[3] == "1")
capable |= LaneCapabilities.CCS;
break;
case 4:
if (flags[1] == "1")
capable |= LaneCapabilities.Degraded;
break;
case 5:
if (flags[1] == "5")
capable |= LaneCapabilities.MLT;
break;
}
}

Seems like a lot of work for a .NET app. Any suggestions?
 
C

Chris R. Timmons

(e-mail address removed) wrote in
I have an enum variable. Is there some way to cast an int or
BitArray and get my enum value? I have to communicate with an
old C-style sever so I get an array of bits("0","1").

Dwight,

The underlying type of an enumeration (if the type isn't explicitly
specified) is an integer (System.Int32). This means that enumeration
values and integer values are interchangeable via casting:

LaneCapabilities capable = (LaneCapabilities) 12;

// capable.ATIM and capable.Degraded are "set".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top