Difference between set and set all in c# Difference between set and set all in c# arrays arrays

Difference between set and set all in c#


That's because SetAll() method looks like that:

public void SetAll(bool value){    int num = value ? -1 : 0;    int arrayLength = BitArray.GetArrayLength(this.m_length, 32);    for (int i = 0; i < arrayLength; i++)    {        this.m_array[i] = num;    }    this._version++;}

BitArray uses int[] internally to store your bits. To get new BitArray(8) it uses just one int, because that's enough to store 8 bits. But the entire allocated memory is used when you use CopyTo method to get int[], so you get all 32 bits from underlying int. and because when you use for loop you only set 8 least meaningful bits you get 255 when cast to int[] after using the loop and -1 when you do that using SetAll() method.

You can prove that.

for (int i = 1; i <= 32; i++){    BitArray bb = new BitArray(i);    bb.SetAll(true);    BitArray bb2 = new BitArray(i);    for (int j = 0; j < i; j++)        bb2.Set(j, true);    int[] dd = new int[1];    int[] dd2 = new int[1];    bb.CopyTo(dd, 0);    bb2.CopyTo(dd2, 0);    Console.WriteLine("{0} - {1}", dd[0], dd2[0]);}

Code above prints:

-1 - 1-1 - 3-1 - 7-1 - 15-1 - 31-1 - 63-1 - 127-1 - 255-1 - 511-1 - 1023-1 - 2047-1 - 4095-1 - 8191-1 - 16383-1 - 32767-1 - 65535-1 - 131071-1 - 262143-1 - 524287-1 - 1048575-1 - 2097151-1 - 4194303-1 - 8388607-1 - 16777215-1 - 33554431-1 - 67108863-1 - 134217727-1 - 268435455-1 - 536870911-1 - 1073741823-1 - 2147483647-1 - -1