Search code examples
c#iequalitycomparer

Can this implementation of an IEqualityComparer be improved?


I don't see any problems with this code, but it feels like I'm missing something. Maybe it is possible to reduce the number of lines. Or is there even a bug to be fixed? I'm open to any suggestions.

public class NameComparer : IEqualityComparer<FileInfo>
{
    public bool Equals (FileInfo x, FileInfo y)
    {
        if (x == null) {
            return y == null;
        }

        if (y == null) {
            return false;   
        }

        return x.Name.Equals (y.Name);
    }

    public int GetHashCode (FileInfo obj)
    {
        return obj.Name.GetHashCode ();
    }
}

Solution

  • You should first return true if the FileInfo's equality operator returns true. Also, specify the type of string comparison you want to do. Presumably you'd want to ignore case, since these are filenames.

    public class NameComparer : IEqualityComparer<FileInfo>
    {
       public bool Equals(FileInfo x, FileInfo y)
       {
          if (x == y)
          {
             return true;
          }
    
          if (x == null || y == null)
          {
             return false;
          }
    
          return string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
       }
    
       public int GetHashCode (FileInfo obj)
       {
          return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.FullName);
       }
    }