Sometimes there is a need to create duplicateinstances of a same class ( objects with same values for the properties, and fields. )
When the class is of known type, it’s easy to duplicate the instances.
For e.g.:
Consider a class called MyClassExample
Class MyClassExample { public int NUMBER1 {get; set;} public int NUMBER2{get; set;} public int number3; public int number4; }
Now we create an instance:
MyClassExample obj1 = new MyClassExample{NUMBER1 =5;NUMBER2 =6; number3 = 7; number4=8 };
To create the duplicate instance, and add it to a collection, we can write like
for(int i=0; i<10; i++) { MyClassExample objNew = new MyClassExample(); objNew.NUMBER1 = obj1. NUMBER1; objNew.NUMBER2 = obj1. NUMBER2; objNew.number3= obj1. number3; objNew.number4= obj1. number4; lstObjectCollection.add(objNew); } Where lstObjectCollection is the List collection of type MyClassExample, List<MyClassExample> lstObjectCollection = new List<MyClassExample>();
But what if the type of an object is unknown, and we need to create duplicate objects from this existing object.
System.Reflection will help in this case.
Activator.CreateInstance() is used to create the new instance of an object.
PropertyInfo & FieldInfo object contains the list of properties & fields associated with an object.
Using these 3 objects and their related functions we can create a brand new instance of an object from an existing object with all the properties and fields value duplicated.
Here is one simple function which can be used to create a duplicate object.
public object CreateDuplicateObject(object originalObject) { //create new instance of the object object newObject = Activator.CreateInstance(originalObject.GetType()); //get list of all properties var properties = originalObject.GetType().GetProperties(); //loop through each property foreach (var property in properties) { //set the value for property property.SetValue(newObject, property.GetValue(originalObject, null), null); } //get list of all fields var fields = originalObject.GetType().GetFields(); //loop through each field foreach (var field in fields) { //set the value for field field.SetValue(newObject, field.GetValue(originalObject)); } // return the newly created object with all the properties and fields values copied from original object return newObject; }
(NOTE:
1. Use reflections only when the type of object is unknown or very random. As reflections may have a cost to performance, use them wisely.
2. The above defined method is only valid for objects containing “value type” properties and fields, like int, float, long. etc.)