From 2b9dc19c62e29e6713c1032728936003db449ffa Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Sat, 11 May 2024 13:34:39 +0200 Subject: [PATCH] Unfinished implementation of RecursiveFieldsEqual. --- AioNet.Reflection/DeepComparison.cs | 54 +++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/AioNet.Reflection/DeepComparison.cs b/AioNet.Reflection/DeepComparison.cs index 85a8cd1..5be99dd 100644 --- a/AioNet.Reflection/DeepComparison.cs +++ b/AioNet.Reflection/DeepComparison.cs @@ -1,4 +1,54 @@ -namespace AioNet.Reflection +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace AioNet.Reflection { - public class DeepComparison { } + public static class DeepComparison + { + public static bool RecursiveFieldsEqual(this T first, T second) + { + Type type = typeof(T); + return first.RecursiveFieldsEqual(second, type); + } + + public static bool RecursiveFieldsEqual(this object first, object second, Type type) + { + // If both are null, return true. + if (first is null && second is null) + { + return true; + } + + // If one of them is null and the other one isn't, return false. + if (first is null || second is null) + { + return false; + } + + // If type is value type or a String, simply return result of Equals. + if (type.IsValueType || type.Equals(typeof(string))) + { + return first.Equals(second); + } + + // If type is IEnumerable, compare individual elements. + if (type.GetInterface("System.Collections.IEnumerable") != null) + { + throw new NotImplementedException(); + } + + IEnumerable fields = type.GetRuntimeFields(); + + return fields.All(field => + { + return RecursiveFieldsEqual( + field.GetValue(first), + field.GetValue(second), + field.FieldType + ); + }); + } + } }