Skip to content

Instantly share code, notes, and snippets.

@Fitzse
Created July 10, 2013 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fitzse/5969917 to your computer and use it in GitHub Desktop.
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.
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;
}
}
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