Skip to content

Instantly share code, notes, and snippets.

@ertanturan
Last active May 13, 2022 11:41
Show Gist options
  • Save ertanturan/85880c4333eee126318d71f74dd72f0f to your computer and use it in GitHub Desktop.
Save ertanturan/85880c4333eee126318d71f74dd72f0f to your computer and use it in GitHub Desktop.
Copy Properties and/or Fields of a class to another
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class ReflectionUtilityExtension
{
public static void CopyPropertiesTo<T, U>(this T source, U dest)
{
List<PropertyInfo> sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList();
List<PropertyInfo> destProps = typeof(U).GetProperties()
.Where(x => x.CanWrite)
.ToList();
foreach (PropertyInfo sourceProp in sourceProps)
{
if (destProps.Any(x => x.Name == sourceProp.Name))
{
PropertyInfo p = destProps.First(x => x.Name == sourceProp.Name);
if (p.CanWrite)
{
p.SetValue(dest, sourceProp.GetValue(source, null), null);
}
}
}
}
public static void CopyFieldsTo<T, U>(this T source, U dest)
{
List<FieldInfo> sourceProps = typeof(T).GetFields().Where(x => x.IsPublic).ToList();
List<FieldInfo> destProps = typeof(U).GetFields()
.Where(x => x.IsPublic)
.ToList();
foreach (FieldInfo sourceProp in sourceProps)
{
if (destProps.Any(x => x.Name == sourceProp.Name))
{
FieldInfo p = destProps.First(x => x.Name == sourceProp.Name);
if (p.IsPublic)
{
p.SetValue(dest, source);
}
}
}
}
public static List<PropertyInfo> GetProperties<T>(this T value)
{
return typeof(T).GetProperties().ToList();
}
public static List<FieldInfo> GetFields<T>(this T value)
{
return typeof(T).GetFields().ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment