C#C
C#13mo ago
eli

Contains returning False despite same hashcode and Equals returning true

            if (!product.QcPhotoSets.Contains(qcPhotoSet))
            {
                var existingQcPhotoSet = product.QcPhotoSets.FirstOrDefault(q => q.Equals(qcPhotoSet));
                
                if (existingQcPhotoSet != null)
                {
                    _logger.LogInformation("Existing QcPhotoSet {QcPhotoSet} already exists", existingQcPhotoSet);
                    _logger.LogInformation("Existing hashcode {ExistingHashCode} New hashcode {NewHashCode}, {Equal}", existingQcPhotoSet.GetHashCode(), qcPhotoSet.GetHashCode(), existingQcPhotoSet.Equals(qcPhotoSet));
                    
                }
                
                _logger.LogInformation("Adding new QcPhotoSet {QcPhotoSet}", qcPhotoSet);
                product.QcPhotoSets.Add(qcPhotoSet); // If it doesn't exist, add it
                hasChanged = true;
            }


In my log output:
Existing hashcode 170042874 New hashcode 170042874, True


My classes: (Have removed irellevant fields)

public class QcPhotoSet
{
    [Required] public ISet<QcPhoto> QcPhotos { get; set; } = new HashSet<QcPhoto>();

    protected bool Equals(QcPhotoSet other)
    {
        return QcPhotos.SetEquals(other.QcPhotos);
    }

    public override bool Equals(object? obj)
    {
        if (obj is null) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != GetType()) return false;
        return Equals((QcPhotoSet)obj);
    }
    
    public override int GetHashCode()
    {
        // Start with the hash of Source
        var hash = (int)Source.GetHashCode();
        
        // XOR all photo hash codes together
        // XOR is commutative, so order doesn't matter
        foreach (var photo in QcPhotos)
        {
            hash ^= photo.GetHashCode();
        }
        
        return hash;
    }

    public override string ToString()
    {
        return $"{Source} Qc Photos: ({string.Join(", ", QcPhotos)})";
    }
}


public class QcPhoto
{
    [Required] public required Uri OriginalPhotoUrl { get; init; }

    protected bool Equals(QcPhoto other)
    {
        return OriginalPhotoUrl.ToString().Equals(other.OriginalPhotoUrl.ToString());
    }

    public override bool Equals(object? obj)
    {
        if (obj is null) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != GetType()) return false;
        return Equals((QcPhoto)obj);
    }

    public override int GetHashCode()
    {
        return OriginalPhotoUrl.GetHashCode();
    }
}
Was this page helpful?