Skip to content

Instantly share code, notes, and snippets.

@pjmagee
Last active June 26, 2022 13:29
Show Gist options
  • Select an option

  • Save pjmagee/991a00e804c1846153b2fc7d0a136421 to your computer and use it in GitHub Desktop.

Select an option

Save pjmagee/991a00e804c1846153b2fc7d0a136421 to your computer and use it in GitHub Desktop.
dynamic field equals
void Main()
{
Model one = new() { Prop1 = null };
Model two = new() { Prop1 = null };
one.GetHashCode().Equals(two.GetHashCode()).Dump("hashcode");
one.Equals(two).Dump("equals");
}
public class Model
{
public string Prop1 { get; set; } = default;
public int Prop2 { get; set; } = default;
public bool Prop3 { get; set; } = default;
public float? Prop4 { get; set; } = default;
public int DefaultZero { get; set; }
private PropertyInfo[]? _properties;
private PropertyInfo[] Properties => (_properties ?? (_properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)));
public override int GetHashCode()
{
return Properties
.OrderBy(p => p.Name)
.Select(p => p.GetValue(this))
.Where(value => value is not null)
.Select(value => value!.GetHashCode())
.Aggregate((total, next) => total ^ next);
}
public override bool Equals(object? obj)
{
foreach (var propertyInfo in Properties)
{
var thisValue = propertyInfo.GetValue(this);
var otherValue = propertyInfo.GetValue(obj);
var equal = object.Equals(thisValue, otherValue);
if (!equal) return false;
}
return true;
}
}
public class Model2
{
public string Prop1 { get; set; } = default;
public int Prop2 { get; set; } = default;
public bool Prop3 { get; set; } = default;
public float? Prop4 { get; set; } = default;
public override int GetHashCode()
{
return Properties
.OrderBy(p => p.Name)
.Select(p => p.GetValue(this))
.Where(value => value is not null)
.Select(value => value!.GetHashCode())
.Aggregate((total, next) => total ^ next);
}
private PropertyInfo[]? _properties;
private PropertyInfo[] Properties => (_properties ?? (_properties = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment