Created
July 10, 2013 20:18
-
-
Save Fitzse/5969917 to your computer and use it in GitHub Desktop.
Extension method to copy all instance parameters with same names/types from once class to another. First one is implementation second is usage.
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 MyExtensions { | |
public static U CopyTo<U>(this Object obj){ | |
var objType = obj.GetType(); | |
var newType = typeof(U); | |
var newInstance = Activator.CreateInstance<U>(); | |
var objProperties = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public); | |
var newProperties = newType.GetProperties(BindingFlags.Instance | BindingFlags.Public); | |
foreach(var prop in objProperties){ | |
var value = prop.GetValue(obj); | |
var newProp = newProperties.SingleOrDefault(x => x.Name == prop.Name && x.PropertyType == prop.PropertyType); | |
if(newProp != null){ | |
newProp.SetValue(newInstance,value,null); | |
} | |
} | |
return newInstance; | |
} | |
} |
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 class ParentClass{ | |
public int Number {get;set;} | |
public string Text {get;set;} | |
} | |
public class ChildClass : ParentClass{ | |
public decimal AnotherNumber {get;set;} | |
public string MoreText {get;set;} | |
} | |
void Main() | |
{ | |
var parent = new ParentClass{ | |
Number = 4, | |
Text = "SOME TEXT" | |
}; | |
var child = parent.CopyTo<ChildClass>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment