namespace Dic { public class Key {     string name;     public Key(string n) { name = n; } }  class Program {     static string Test()     {         Key a = new Key("A");         Key b = new Key("A");         System.Collections.Generic.Dictionary<Key, int> d = new System.Collections.Generic.Dictionary<Key, int>();         d.Add(a, 1);         return d.ContainsKey(b).ToString();     }      static void Main(string[] args)     {         System.Console.WriteLine(Test());     } } } What should I change to get true?
Dictionary is not Thread-Safe.
Remarks. The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.
The default constructor of C# Dictionary class constructs a Dictionary object, in which the keys are case sensitive. So when you insert data pairs <Key, Value> and <key, Value>, they are regarded as two different items.
You want true - but a and b are different objects.
You need to override GetHashCode and Equals on class Key
public class Key {     string name;     public Key(string n) { name = n; }      public override int GetHashCode()     {         if (name == null) return 0;         return name.GetHashCode();     }      public override bool Equals(object obj)     {         Key other = obj as key;         return other != null && other.name == this.name;     } } If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With