I have an Object with many properties and i need to create a copy of that object in each iteration such that all properties copied in new born object with their last set value. (I can't Copy all properties and their values one by one, because my object is actually a custom user control which has many properties and I don't know all of them!)
Asked
Active
Viewed 4,831 times
1
-
What have you tried? Please show object. Why can't copy properties one by one? – Gilad Green Sep 03 '17 at 07:38
-
the object actually is my own created user control. I don'n know all properties of the user control!! – MohsenCs Sep 03 '17 at 07:40
-
@ReyanChougle, Thanks for your comment, I can not implement a Custom Clone function, because my object is a user control and has lots of Properties. – MohsenCs Sep 03 '17 at 07:47
1 Answers
2
You can use this extension method to copy all object fields and properties.There can be some errors when you try to copy fields and properties,that are reference type.
public static T CopyObject<T>(this T obj) where T : new()
{
var type = obj.GetType();
var props = type.GetProperties();
var fields = type.GetFields();
var copyObj = new T();
foreach (var item in props)
{
item.SetValue(copyObj, item.GetValue(obj));
}
foreach (var item in fields)
{
item.SetValue(copyObj, item.GetValue(obj));
}
return copyObj;
}

David Mkheyan
- 518
- 6
- 15