views:

126

answers:

3

Hello

I have a business class which I need to serialize to xml. It has a BitArray property.

I have decorated it with [XmlAttribute] but the serialization is failing with

To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.Boolean) at all levels of their inheritance hierarchy. System.Collections.BitArray does not implement Add(System.Boolean).

I am not sure whether its possible to serialize to xml?

If not what would be an efficient means of serializing the BitArray

Thanks for looking

A: 

Do you know if this means that you do not have a Setter on your property (typically required when serializing things) or if this means that the data type is not serializable?

Jaxidian
A: 

As something quick and dirty, how about create a property which has the [XmlAttribute], and it's getter return an array created from your BitArray by using the static BitArray.CopyTo method?

paquetp
+1  A: 

You cannot directly serialize a BitArray to XML. The reason is that in order to de-serialize it you'd need an Add method which BitArray doesn't supply.

You can, however, copy it to an array that can be serialized:

BitArray ba = new BitArray(128);
int[] baBits = new int[4];  // 4 ints makes up 128 bits

ba.CopyTo(baBits, 0);
// Now serialize the array

Going the other way involves deserializing the array and calling the BitArray constructor:

int[] baBits;  // This is deserialized somehow
BitArray ba = new BitArray(baBits);

If you do this, you'll want your BitArray size to be a multiple of the word size (i.e. if you use an array of int, then your BitArray size should be a multiple of 32).

Jim Mischel