Created
January 14, 2013 09:38
-
-
Save jonathascosta/4528916 to your computer and use it in GitHub Desktop.
Copy properties from an object to another object
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
| public void CopyProperties(object from, object to) | |
| { | |
| foreach (var p in ((object)from).GetType().GetProperties()) | |
| { | |
| var toProperty = to.GetType().GetProperty(p.Name); | |
| var fromValue = p.GetValue(from, null); | |
| if (toProperty.PropertyType.IsValueType) | |
| { | |
| var convertedValue = Convert.ChangeType(fromValue, toProperty.PropertyType); | |
| toProperty.SetValue(to, convertedValue, null); | |
| } | |
| else | |
| CopyProperties(toProperty.GetValue(to, null), fromValue); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment