Created
June 12, 2019 20:33
-
-
Save InvaderZim85/df970744acfc60c5abc89f0f8b000e55 to your computer and use it in GitHub Desktop.
Method to compare two objects of the same type for equality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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