From 8682f50500523b5f9ca8410e92e96eb16b1f2ac4 Mon Sep 17 00:00:00 2001 From: Jordan Wages Date: Wed, 29 Jan 2025 23:57:59 -0600 Subject: [PATCH] Added property transfer --- CapyKit/CapyKit.csproj | 2 +- CapyKit/Extensions/ObjectExtensions.cs | 52 ++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 CapyKit/Extensions/ObjectExtensions.cs diff --git a/CapyKit/CapyKit.csproj b/CapyKit/CapyKit.csproj index 38cabc9..eedf8d7 100644 --- a/CapyKit/CapyKit.csproj +++ b/CapyKit/CapyKit.csproj @@ -6,7 +6,7 @@ enable True README.md - 1.0.2 + 1.0.3 diff --git a/CapyKit/Extensions/ObjectExtensions.cs b/CapyKit/Extensions/ObjectExtensions.cs new file mode 100644 index 0000000..8cd041e --- /dev/null +++ b/CapyKit/Extensions/ObjectExtensions.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CapyKit.Extensions +{ + /// An class containing extenstions that apply to any object type. + public static class ObjectExtensions + { + /// + /// An object extension method that updates the properties of a given + /// object with the values from a given object. + /// + /// Generic type parameter. + /// The target object to act on. + /// Source for the new property values. + public static void UpdateProperties(this T target, T source) + { + var properties = typeof(T).GetProperties(); + foreach (var prop in properties) + { + if (prop.CanWrite) + { + prop.SetValue(target, prop.GetValue(source)); + } + } + } + + /// + /// An object extension method that updates the properties of a given + /// object with the values from a given object. + /// + /// The target object to act on. + /// Source for the new property values. + public static void UpdateProperties(this object target, object source) + { + var targetProperties = target.GetType().GetProperties(); + var sourceProperties = source.GetType().GetProperties(); + var matchingProperties = targetProperties.Join(sourceProperties, outer => new { outer.Name, outer.PropertyType }, inner => new { inner.Name, inner.PropertyType }, (outer, inner) => new { Target = outer, Source = inner }); + + foreach (var propertyMatch in matchingProperties) + { + if(propertyMatch.Target.CanWrite) + { + propertyMatch.Target.SetValue(target, propertyMatch.Source.GetValue(source)); + } + } + } + } +}