tags:

views:

37

answers:

3

I need to store an array of flags in a string. I was looking at using BitArray, but noticed that there is no built-in method to write to/read from a char[] or int[] or something. I can write this code easily enough, but I'd prefer to use a built-in method if there is one out there.

So are there built-in .NET methods that handle this?

+2  A: 

If your flags are represented as a defined enum, you can simply cast it to one of the integral types that enums support (int, long, etc). You can then deserialize the enum from its value representation using:

// define a Flags enumeration...
[Flags] enum MyEnum { First = 1, Second = 2, Third = 4, };


MyEnum originalValue = MyEnum.First | MyEnum.Second;
int storedValue = (int)originalValue;  

// value serialized into storage somewhere...

// later on ...
// deserialized however you need...
int restoredValue = ReadValueFromDataStore(); 
// convert back into a typesafe enum...
MyEnum recoveredValue = Enum.Parse( typeof(MyEnum), restoredValue );
LBushkin
Actually, it is possible to use originalValue.ToString() and Enum.Parse to serialize and deserialize the value - the intermediate int isn't needed. Is there a reason the intermediate int is needed?
dmo
A: 

The BitConverter class has some of this functionality.

dmo
A: 

The BitArray does support Int32[], you can use the constructor that accepts an int[] for initialization, and CopyTo(Array array, Int32 index). The current CopyTo implementation supports writing to Boolean[], Byte[] and Int32[] according to msdn.

Simon Svensson