Hi Friends,
In this post we shall see how we can clone the properties of a abstract class.
If there is a normal class and we need to clone it, then we will use the simple method of cloning
1) Create a new object
2) Copy all the properties of this object to the newly created object
3) Return the object
But assume a condition when we have a abstract class in which lot of properties are been defined and it has lot of derived classes. Now if we want all the derived classes to implement clone and clone all the properties of the base class then we need to write clone method in each derived classes. Since we know that we cannot create a instance method in abstract class becuase its instance cannot be created.
What would you do in the following case, here is the solution for it, Its simple and a generic method that can be used in any class that needs to implement clone. Here it goes.
Clone Properties:
abstract class CloneProperties: ICloneable
{
public int fldi = 0;
int propi = 0;
public int Propi
{
get { return propi; }
set { propi = value; }
}
int propj = 0;
public int Propj
{
get { return propj; }
set { propj = value; }
}
#region ICloneable Members
public object Clone()
{
//we create a new instance of this specific type.
object newInstance = Activator.CreateInstance(this.GetType());
//We get the array of properties for the new type instance.
PropertyInfo[] properties = newInstance.GetType().GetProperties();
int i = 0;
foreach (PropertyInfo pi in this.GetType().GetProperties())
{
properties[i].SetValue(newInstance, pi.GetValue(this, null), null);
i++;
}
return newInstance;
}
#endregion
}
To check the output we shall create a dummy class and inherit it from cloneProperties class
class Prop : CloneProperties
{
}
And in the Main function we shall call the clone and check
class Program
{
static void Main(string[] args)
{
CloneProperties cloneProp1 = new Prop();
cloneProp1.fldi = 1;
cloneProp1.Propi = 2;
cloneProp1.Propj = 3;
CloneProperties cloneProp2 = (CloneProperties)cloneProp1.Clone();
Console.WriteLine("Cloning Properties");
Console.WriteLine("fldi = {0} , Propi = {1}, Propj = {2}", cloneProp2.fldi, cloneProp2.Propi,cloneProp2.Propj);
Console.Read();
}
}
Output:
Well it has worked fine, we can see that only the properties are succesfully cloned so they have got the values 2 and 3 and for fields it dint clone and it has value 0.
Clone Fields:
If you need to clone only the fields then you can replace the above clone function with the below one
public object Clone()
{
//we create a new instance of this specific type.
object newInstance = Activator.CreateInstance(this.GetType());
//We get the array of properties for the new type instance.
FieldInfo[] fields = newInstance.GetType().GetFields();
int i = 0;
foreach (FieldInfo fi in this.GetType().GetFields())
{
fields[i].SetValue(newInstance, fi.GetValue(this));
i++;
}
return newInstance;
}
Here you can see that only fields are cloned and properties are set to the default vaule.
Happy Learning