Royi Namir
Royi Namir

Reputation: 148524

BitArray doesn't work as expected

I have this BitArray :

    BitArray bits = new BitArray(2);
    bits[0] = false;
    bits[1] = true;

Which represents : 10b --> 2

Let's see what's its value :

  int[] array = new int[1];
  bits.CopyTo(array, 0);
  Console.WriteLine(array[0]);  // value=2

Great.

Now I'm changing the first code to :

   bool[] bits = new bool[2] {  false, true }; //same value !
   BitArray myBA4 = new BitArray( bits );

   //and again...
   int[] array = new int[1];
   bits.CopyTo(array, 0);
   Console.WriteLine(array[0]);

Question

Where is my mistake ? I think it should be same result.

Upvotes: 1

Views: 356

Answers (1)

AlexD
AlexD

Reputation: 32566

bool[] bits = new bool[2] { false, true };

allocates an array of two elements, and CopyTo is supposed to copy them one by one. It cannot succeed because

  • the second array is too short;
  • bool cannot be converted to int implicitly.

Upvotes: 2

Related Questions