I created a sort of string wrapper class and want to use its instances as dictionary keys interchangeably with usual strings. I overrode GetHashCode
and Equals
and got results that seem strange. I've isolated the issue. Please look at my code and explain me why does second lookup returns null.
void Main()
{
var foo = new StringWrapper("foo");
var h = new Hashtable {{ foo, "bar" }};
Console.WriteLine(h["foo"]);
Console.WriteLine(h[foo]); // null ??
}
public class StringWrapper
{
readonly string wrapped;
public StringWrapper(string s) {
wrapped = s;
}
public override bool Equals(object obj) {
return wrapped.Equals(obj);
}
public override int GetHashCode() {
return wrapped.GetHashCode();
}
public override string ToString() {
return wrapped;
}
}