0

Below is a sample of my dictionary definition. When I define DicKeys as a class, ContainsKey() doesn't work. If I change DicKeys to a struct, it works properly.

Why does ContainsKey() work differently for a class than it does for a struct?

Dictionary<DicKeys, DicVals> aDic = new Dictionary<DicKeys, DicVals>();

// original version as below
public Class DicKeys 
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// revised version as below
public struct DicKeys
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// common parts of code below
public enum EnKey1 
{
   A1,
   A2,
}

public enum EnKey2 
{
   B11,
   B12,
}

DicKeys aDicKey = new DicKeys();
// assigned value to aDicKey obj here;

if (aDic.ContainsKey(aDicKey ) == true)  
{
 // do some thing here
 // If I defined as 'class', it doesn't hit here.
 // Updated to 'struct', it hit here.
}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Nano HE
  • 9,109
  • 31
  • 97
  • 137

1 Answers1

4

Well, you haven't shown where you're populating the dictionary or what sfTKey is... but I strongly suspect it's because you haven't overridden Equals or GetHashCode in DicKeys.

By default, classes use reference identity for equality - in other words, two key references will only compare as equal if they refer to the exact same object. You can override Equals and GetHashCode to provide equality based on the contents of the objects though. Value types (structs) automatically use value-based equality, but I certainly wouldn't recommend using a mutable struct as you've got here. (I wouldn't recommend using public fields at all, to be honest.)

See this question for an example of the kind of thing you might do in Equals and GetHashCode - and some other members you may want to provide on types which have value-based equality.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Sorry, `sfTKey` should be `aDicKey`. It was validated and assigned successfully for my case. I am sure that it caused by the Key words of `class` or `struct` based on my practic. – Nano HE Dec 14 '10 at 09:52
  • @Nano: Changing the name of the variable doesn't make any difference. You still haven't shown where you're populating the dictionary. – Jon Skeet Dec 14 '10 at 09:53
  • Yes, it din't do any overridden operations for `Equals` or `GetHashCode` in my completed code. I would step into it. Thanks. – Nano HE Dec 14 '10 at 09:58