[Mono-dev] Key matching issue in generic Dictionary [correct message]
Generic 2006
generic2006 at libero.it
Wed Aug 23 10:52:56 EDT 2006
On 08/23/2006 04:35 PM, Brian Crowell wrote:
> Generic 2006 wrote:
>> I'm facing a strange behavior affecting
>> System.Collections.Generic.Dictionary<TKey,TValue>: when I try to
>> search for a key among the dictionary entries using interface members
>> such as ContainsKey(<TKey> key) or this[<TKey> key] I receive wrong
>> responses (the key can't be find, whilst it's really there!).
>> I supposed that it could be a problem on the TKey side (where I
>> implemented System.IEquatable<TKey>), so I put some Console.WriteLine()
>> inside the code to verify. A System.Collections.Generic.Dictionary
>> instance is incapsulated in MyDictionary (an implementation of
>> generic IDictionary), TKey is assigned to Name type, TValue is
>> irrelevant.
>
> IEquatable<T> is not enough. You need to override Object.GetHashCode()
> and Object.Equals(). IEquatable<T> is optional, GetHashCode and Equals
> are mandatory.
>
> --Brian
>
Thank you Brian for your prompt reply: I've just got an analogous hint
from the guys at IRC #mono.
So I should write something like this (please, let me know):
class Name : IEquatable<Name>
{
public Name(string value)
{
...
}
// Mandatory!!!
public override int GetHashCode()
{
return this.value.GetHashCode();
}
// Mandatory!!!
public override bool Equals(object obj)
{
if(obj is Name) return Equals((Name)obj);
else return false;
}
public bool Equals(Name obj)
{
Console.WriteLine("Name.Equals(): this: " + this.value + " other: " + obj.Value);
return this.value.Equals(obj.Value);
}
public string Value
{
get{return this.value;}
}
}
More information about the Mono-devel-list
mailing list