Last active
September 11, 2022 21:43
-
-
Save pedrohenriquebr/f62ed7f0ffab98753ed3ebc0418a99b5 to your computer and use it in GitHub Desktop.
Extensions Methods for casting base class to derived class for inheritance object mappers
This file contains hidden or 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
| namespace Reflection.Extensions; | |
| public static class ReflectionExtensions | |
| { | |
| public static object? GetPropertyValue(object obj, string propertyName) | |
| { | |
| var propertyInfo = obj.GetType().GetProperty(propertyName); | |
| return propertyInfo?.GetValue(obj); | |
| } | |
| public static void SetPropertyValue(object obj, string propertyName, object value) | |
| { | |
| var propertyInfo = obj.GetType().GetProperties().FirstOrDefault(x => x.Name == propertyName); | |
| propertyInfo?.SetValue(obj, value); | |
| } | |
| public static TChild? CastToChild<TParent, TChild>(this TParent parent) | |
| where TChild : TParent | |
| where TParent : class | |
| { | |
| var created = Activator.CreateInstance(typeof(TChild)); | |
| Type parentType = typeof(TParent); | |
| Type childType = typeof(TChild); | |
| var parentProps = parentType.GetProperties() | |
| .Select(x => x.Name); | |
| var childProps = childType.GetProperties() | |
| .Select(x => x.Name) | |
| .Intersect(parentProps); | |
| foreach (var propName in childProps) | |
| { | |
| var parentValue = GetPropertyValue(parent,propName); | |
| SetPropertyValue(created, propName, parentValue); | |
| } | |
| return (TChild)created; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment