The problem is not in the code you've shown here.
The problem is that, if you want to use instances of a custom class as keys in a dictionary, you need to properly overload Equals
and GetHashCode
.
As LordTakkera put it:
The default comparer [for a class] will check if they are actually the same object (which of course they are not).
Note that:
Object.Equals("foo", "foo"); // returns true
But
Object.Equals(new ChArray("foo"), new ChArray("foo")); // returns false
A proper override of those two functions will provide the correct result.
This should work:
public class ChArray {
// (as you have it)
public override bool Equals(System.Object obj)
{
// If parameter cannot be cast to ChArray return false:
ChArray p = obj as ChArray;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return m_str == p.m_str;
}
public bool Equals(ChArrayp)
{
// Return true if the fields match:
return m_str == p.m_str;
}
public override int GetHashCode()
{
return m_str.GetHashCode();
}
}