Created
September 1, 2020 13:09
-
-
Save digioz/864218b57596a99ae1d765a33652898b to your computer and use it in GitHub Desktop.
Property Copy between two C# Objects
This file contains 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
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