Compare two objects with reflection

suggest change
public class Equatable
{
    public string field1;

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;

        var type = obj.GetType();
        if (GetType() != type)
            return false;

        var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        foreach (var field in fields)
            if (!Equals(field.GetValue(this), field.GetValue(obj)))
                return false;

        return true;
    }

    public override int GetHashCode()
    {
        var accumulator = 0;
        var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        foreach (var field in fields)
            var value = field.GetValue(this);
            accumulator = unchecked((accumulator * 937) ^ (value == null ? 0 : value.GetHashCode()));

        return accumulator;
    }
}

Note: this example does a field-based comparison (it ignores static fields and properties) for simplicity. Equals is used so boxed value types compare by value, not by box identity.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents