4

I'm trying to do a short simulation where i needed a small bit array, and I chose System.Collections.Specialized.BitVector32.

I'm running it inside a single-threaded object, in a single-threaded loop about 1,000,000 times, each time for indexes {0,1,2}.

Here is the code:

private System.Collections.Specialized.BitVector32 currentCalc 
    = new System.Collections.Specialized.BitVector32();

private void storeInCurrent(int idx, bool val)
{
    currentCalc[idx] = val;
    if (currentCalc[idx] != val)
    {
        throw new Exception("Inconceivable!");
    }
}

To my understanding, the exception should not be thrown, but sometimes it does! An exception is not thrown every time, but in a fair percent - a CONSTANT 1/6 of the time! (which is even stranger)

What am I doing wrong?

codekaizen
  • 26,990
  • 7
  • 84
  • 140
Kaneti
  • 93
  • 6

1 Answers1

6

Look at MSDN; the indexer takes the mask, not the index. So that is:

int mask = 1 << idx;

then use currentCalc[mask]

This is odd though; if you are happy enough to use masks - why would one be using BitVector32, rather than just an int. I also assumed the indexer would take the index. VERY odd design decision.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • same OS I'm using. same output. but your repro makes me think it's even weirder than i thought... – Kaneti Jul 03 '10 at 07:13
  • still, there should be some consistency between GET and SET... thanks. – Kaneti Jul 03 '10 at 07:19
  • The documentation does refer to the `bit` parameter as a *mask*. Basically it sets or clears the bits in the mask. But it's certainly not the clearest doc in the world... nor does this explain the OP's problem (I *think*). – Jon Skeet Jul 03 '10 at 07:19
  • When all else fails, read the docs! Reminds me of the "select is broken" story... – codekaizen Jul 03 '10 at 07:19
  • @Kaneti - there is also `BitVector32.CreateMask(index);` that might be of interest. – Marc Gravell Jul 03 '10 at 07:20
  • @Jon - well, it does. Setting a mask on zero does nothing. And getting a mask from 0 and comparing to the mask (0) will always be true, regardless of the value. – Marc Gravell Jul 03 '10 at 07:21
  • @Kaneti - see my reply to Jon re get/set not "agreeing". This only applies with mask 0. – Marc Gravell Jul 03 '10 at 07:25
  • @Marc: Yup, I was more referring to your sample code. Sorry for not being clear. – Jon Skeet Jul 03 '10 at 07:52
  • @!codekaizen: "select is broken" = http://www.codinghorror.com/blog/2008/03/the-first-rule-of-programming-its-always-your-fault.html – Kaneti Jul 03 '10 at 19:28