Problem: Custom Object implements EqualityComparer and IEquatable, but Dictionary doesn't always use these methods.
Context: I have created a helper class, FilePath
for dealing with file paths instead of treating them as strings. The helper class is responsible for determining if two file paths are equal. I then need to store FilePaths in a Dictionary<FilePath, object>
.
Goal:
Assert.True(new FilePath(@"c:\temp\file.txt").Equals(
new FilePath(@"C:\TeMp\FIle.tXt"));
var dict = new Dictionary<FilePath, object>
{
{new FilePath(@"c:\temp\file.txt"), new object()}
}
Assert.True(dict.ContainsKey(new FilePath(@"c:\temp\file.txt"));
Assert.True(dict.ContainsKey(new FilePath(@"C:\TeMp\FIle.tXt"));
I've created my FilePath class: public class FilePath : EqualityComparer, IEquatable { private string _fullPath;
public FilePath (string fullPath)
{
_fullPath = Path.GetFullPath(fullPath);
}
public override bool Equals(FilePath x, FilePath y)
{
if (null == x || null == y)
return false;
return (x._fullPath.Equals(y._fullPath, StringComparison.InvariantCultureIgnoreCase));
}
public override int GetHashCode(FilePath obj)
{
return obj._fullPath.GetHashCode();
}
public bool Equals(FilePath other)
{
return Equals(this, other);
}
public override bool Equals(object obj)
{
return Equals(this, obj as FilePathSimple);
}
}
Question:
Assert 1 and 2 pass, but Assert 3 fails:
Assert.True(dict.ContainsKey(new FilePath(@"C:\TeMp\FIle.tXt"));