My problem is ContainsKey is always returning false even when they key has been added and .Equals evaluates to true.
I have the following class:
public class StatisticsFilter
{
private String someString1;
private String someString2;
.....
public override string ToString()
{
return string.Format("{0}-{1}-{2}-{3}-{4}", someString1, someString2, ...)
}
public override bool Equals(object obj)
{
return obj.ToString().Equals(ToString());
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
}
I then have a dictionary that looks like this:
private readonly IDictionary<StatisticsFilter, Statistics> _filteredStatisticsDict =
new Dictionary<StatisticsFilter, Statistics>();
....
{
// ALWAYS EVALUATES TO FALSE!
if (_filteredStatisticsDict.ContainsKey(statisticsFilter) == false)
{
_filteredStatisticsDict.Add(statisticsFilter, new Statistics());
}
}
Unable to reproduce with the code you've given us.
Are expecting the 'ToString()' to be the key? I think you will get the desired result by changing the Dictionary declaration to:
Dictionary<string, Statistics>
If I understand what you are trying to accomplish, this should work. With this method the dictionary key is based on the content of the filter.