2

Possible Duplicate:
When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?

This one is funky. I can't get to the bottom of it with ease. Found an exception in the log and dug out some old code. Don't ask me about why this is written this way because I have no idea. The question really is what could be conditions for IndexOutOfRangeException to be thrown when the Item of the dictionary is being set. Here is how the thing looks:

public MyEnum { Undefined = 0, B = 1, C = 2, D = 16, All = B | C | D }

public class MC 
{
  private int _hashCode;
  private int _i;
  private MyEnum _e;

  public MC(int i, MyEnum e)
  {
     _i = i;
     _e = e;
     SetHashCode();
  }

  private SetHashCode()
  {
    _hashCode = _i * 31 + (int)e;
  }

  public override bool Equals(object other)
  {
    if (!(obj is MC))
    {
      return false;
    }
    MC other = (MC)obj;
    return ((_i == other._i) && (_e == other._e));
  }

  public override int GetHashCode()
  {
    return _hashCode;
  }
}

...

var d = new Dictionary<MC, DateTime>();
...
// Create and populate the list of MCs
var mcs = new List<MC>();
...
foreach (MC mc in mcs) 
{
  ...
  d[mc] = DateTime.UtcNow; // Pukes here
}

And the exception is:

System.IndexOutOfRangeException, Source: mscorlib    Index was outside the bounds of the array.       at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)

Ideas how to make the line to fail? Don't what to diverge your attention to the wrong direction but I thought there was something fishy with the Equals and GetHashCode but I couldn't prove it so far - no repro using a unit testing framework.

Community
  • 1
  • 1
Schultz9999
  • 8,717
  • 8
  • 48
  • 87
  • 3
    is this multi-threaded code that throws the error? – Mitch Wheat Oct 11 '11 at 00:21
  • What version of the framework are you running against? – LukeH Oct 11 '11 at 00:22
  • @MitchWheat: good question. Yes, it is. And in fact I did overlook the important thing that dictionary is actually a static member of the worker class that performs that assignment. – Schultz9999 Oct 11 '11 at 00:23
  • 1
    I'd say this might be the answer: http://stackoverflow.com/questions/1920864/when-does-a-dictionary-throw-an-indexoutofrangeexception-on-add-or-containskey. Voted to close as a dup. – Schultz9999 Oct 11 '11 at 00:25

1 Answers1

3

The error you are getting is often caused by multi-threaded, un-locked concurrent access to a dictionary.

See: When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541