Skip to content

Instantly share code, notes, and snippets.

@InvaderZim85
Created June 12, 2019 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InvaderZim85/df970744acfc60c5abc89f0f8b000e55 to your computer and use it in GitHub Desktop.
Save InvaderZim85/df970744acfc60c5abc89f0f8b000e55 to your computer and use it in GitHub Desktop.
Method to compare two objects of the same type for equality
/// <summary>
/// Compares two objects for equality
/// </summary>
/// <typeparam name="T">The type of the object</typeparam>
/// <param name="first">The first object</param>
/// <param name="second">The second object</param>
/// <returns>true when the objects are equal, otherwise false</returns>
public static bool CompareObjects<T>(T first, T second)
{
// Check if the references are equal
if (ReferenceEquals(first, second))
return true;
// Check if any value is null
if (first == null || second == null)
{
return first == null && second == null;
}
// Check for every propery
foreach (var property in first.GetType().GetProperties())
{
var value = property.GetValue(first);
var otherValue = property.GetValue(second);
if (value == null && otherValue == null)
continue;
if (value == null)
return false;
if (!value.Equals(otherValue))
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment