Skip to content

Instantly share code, notes, and snippets.

@digioz
Created September 1, 2020 13:09
Show Gist options
  • Save digioz/864218b57596a99ae1d765a33652898b to your computer and use it in GitHub Desktop.
Save digioz/864218b57596a99ae1d765a33652898b to your computer and use it in GitHub Desktop.
Property Copy between two C# Objects
public static class ValueInjecter
{
public static void CopyPropertiesTo<T, TU>(this T source, TU dest) {
var sourceProps = typeof(T).GetProperties().Where(x => x.CanRead).ToList();
var destProps = typeof(TU).GetProperties()
.Where(x => x.CanWrite)
.ToList();
foreach (var sourceProp in sourceProps) {
if (destProps.Any(x => x.Name == sourceProp.Name)) {
try {
var p = destProps.First(x => x.Name == sourceProp.Name);
// check if the property can be set or no.
if (p.CanWrite) {
p.SetValue(dest, sourceProp.GetValue(source, null), null);
}
}
catch { }
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment