Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary.ContainsKey return False, but a want True

Tags:

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?

like image 744
SkyN Avatar asked Jun 10 '10 13:06

SkyN


People also ask

Is Dictionary Containskey thread safe?

Dictionary is not Thread-Safe.

Is Containskey case sensitive?

Remarks. The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.

Is Dictionary Containskey case sensitive C#?

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.


1 Answers

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;     } } 
like image 64
Itay Karo Avatar answered Sep 23 '22 18:09

Itay Karo