/// <summary> ///Object Copy/// </summary> /// <param name= "obj" >The object being copied</param> /// <returns>New Object</returns> Private ObjectCopyojbect (Objectobj) { if(obj = =NULL) { return NULL; } Object Targetdeepcopyobj; Type TargetType=obj. GetType (); //value type if(Targettype.isvaluetype = =true) {Targetdeepcopyobj=obj; } //Reference type Else{targetdeepcopyobj= System.Activator.CreateInstance (TargetType);//To create a reference objectsystem.reflection.memberinfo[] Membercollection =obj. GetType (). GetMembers (); foreach(System.Reflection.MemberInfo memberinchmembercollection) { //Copy Field if(member. MemberType = =System.Reflection.MemberTypes.Field) {System.Reflection.FieldInfo Field
=(System.Reflection.FieldInfo) member; Object Fieldvalue=field. GetValue (obj); if(Fieldvalue isicloneable) {field. SetValue (Targetdeepcopyobj, (Fieldvalue asicloneable). Clone ()); } Else{field. SetValue (Targetdeepcopyobj, Copyojbect (Fieldvalue)); } }//Copy Properties Else if(member. MemberType = =System.Reflection.MemberTypes.Property) {System.Reflection.PropertyInfo my Property=(System.Reflection.PropertyInfo) member; MethodInfo Info= Myproperty.getsetmethod (false); if(Info! =NULL) { Try { ObjectPropertyValue = Myproperty.getvalue (obj,NULL); if(PropertyValue isicloneable) {Myproperty.setvalue (Targetdeepcopyobj, (PropertyValue asICloneable). Clone (),NULL); } Else{myproperty.setvalue (targetdeepcopyobj, Copyojbect (PropertyValue),NULL); } } Catch(System.Exception ex) {}} } } } returnTargetdeepcopyobj; }
C # Deep Copy reflection implementation