I have been using resharper to generate my equality members, which has really helped with my unit testing.
However it doesn’t seem to work well when my object contains a list.
public class FileandVersions
{
public string fileName { get; set; }
public string assetConfigurationType { get; set; }
public List<Versions> Versions { get; set; }
protected bool Equals(FileandVersions other)
{
return string.Equals(fileName, other.fileName) && string.Equals(assetConfigurationType, other.assetConfigurationType) && Equals(Versions, other.Versions);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((FileandVersions) obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (fileName != null ? fileName.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (assetConfigurationType != null ? assetConfigurationType.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (Versions != null ? Versions.GetHashCode() : 0);
return hashCode;
}
}
}
and here is the definition of the version object.
public class Versions
{
public string versionNumber { get; set; }
public DateTime acctivationTime { get; set; }
public string URL { get; set; }
protected bool Equals(Versions other)
{
return string.Equals(versionNumber, other.versionNumber) && acctivationTime.Equals(other.acctivationTime) && string.Equals(URL, other.URL);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Versions) obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (versionNumber != null ? versionNumber.GetHashCode() : 0);
hashCode = (hashCode*397) ^ acctivationTime.GetHashCode();
hashCode = (hashCode*397) ^ (URL != null ? URL.GetHashCode() : 0);
return hashCode;
}
}
}
Comparison of these object are failing, even when the object are equivalent. Whats the best way to write equality members when the object contains a list?
You should replace the
Equals(Versions, other.Versions)of the equality expression with this:This expression is true when
Versionsarenull, orVersionsare notnull, and they contain the same elements in the same order