3

Am Facing a problem in Dictionaries. Whether an Array can be a Key of a Value???

Dictionary<string[], int> di = new Dictionary<string[], int>();
di.Add(new string[]
{
    "1","2"
}, 1);

di.Add(new string[]
{
    "2","3"
}, 2);

MessageBox.Show(di[new string[] { "2", "3" }].ToString()); // Here KeyNotFoundException occurred.

Why Exception?

Gokul E
  • 1,356
  • 2
  • 13
  • 28
  • 2
    The problem is that each array is considered different according to its `GetHashCode()`, even if they contain the same values. – Matthew Watson Mar 11 '14 at 08:49

3 Answers3

10

By default only references of the arrays would be compared, so you either have to

  1. provide a custom IEqualityComparer<string[]> or
  2. use a Tuple<string, string> as key instead ( since you only have two strings)

Here's a similar question's answer which shows how to create a custom comparer for the Dictionary- constructor.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thus I need to Create a Multikeyed Dictionary of N number of Keys dynamically.. I tried a simple.. your answer gives me a way.. :-) – Gokul E Mar 11 '14 at 08:55
  • 1
    @GokulJai: i'm not sure if you've understood me correctly. The [`Tuple`](http://msdn.microsoft.com/en-us/library/dd387181%28v=vs.110%29.aspx) is just an alternative for your array since you're using only two strings anyway. A `Tuple` overrides `Equals` + `GetHashCode` automatically for you. If you want to use the array you need to provide a custom class that implements `IEqualityComparer` which you use in the constructor of the dictionary. – Tim Schmelter Mar 11 '14 at 09:01
  • yes I understood this. My `Key` array can contain one or more elements in it.. but I should use the Custom Comparer. @TimSchmelter thank you. – Gokul E Mar 11 '14 at 10:24
3

No, actually you should not use arrays as a Dictionary<> Key; Dictionary<> when works with keys uses their hash codes which are computed as addresses:

String[] a = new[]{"1", "2"}; 
String[] b = new[]{"1", "2"}; 

a.GetHashCode() == b.GetHashCode(); // <- false

Arrays a and b have different addresses, and so different hash codes that's why

di.Add(a, 1); 
di[b]; // <- error since a.GetHashCode() != b.GetHashCode() 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Because a the Equals and GetHashCode functions of an array don't compare the content but the reference of the array himself.

Gerard Walace
  • 921
  • 7
  • 10