Home > C# Code > A generic cloning method

A generic cloning method

Hey all,

As you know I’m big on Reflection, and big on Generics…now, here’s a method that combines the two for a neat little cloning tool.

Let’s assume we have a base object we use for objects, and let’s call it DataObject.  Anything can derive from this object, and in addition, I’m going to add the following method to allow me to “clone” the properties of my current object onto the properties of any other object, provided the Name and Type of the property match.

Notice that I am using the generic t notation for a generic object, and this becomes a generic method.

public class DataObject

{

public t Clone<t>()
{
     //reflection based clone
     Type tType = typeof(t);

     t item = (t) Activator.CreateInstance(tType);

     PropertyInfo[] props = tType.GetProperties();

     foreach (PropertyInfo prop in props)
     {
          try
          {
                 prop.SetValue(item, prop.GetValue(this, null), null);
          }
          catch { }
     }  

     return item;
}

}

 

Ok, now that that’s done, let’s create two more classes, a Dog, and a Cat.

 

public class Cat : DataObject

{

private string _name;

public string Name

{

    get { return _name;}

    set { _name = value;}

}

private string _color;

public string Color

{

    get { return _color;}

    set { _color= value;}

}

}

public class Dog : DataObject

{

private string _name;

public string Name

{

    get { return _name;}

    set { _name = value;}

}

private string _color;

public string Color

{

    get { return _color;}

    set { _color= value;}

}

}

 

Ok, let’s create a Cat.

Cat cat = new Cat();

cat.Name = “Fluffy”;

cat.Color = “Orange”;

Now that we have that, we can create a Dog from the Cat:

Dog dog = cat.Clone<Dog>();

Once this method is called, the dog will have the exact same properties as the cat…this is useful in particular if you are adjusting properties on objects that are similar enough while in a loop (for example, you are looping on creating email objects that you are placing in a list) and you find yourself in a position where just overriding the properties on the current object won’t work.

Happy cloning!

 

Rob

Advertisements
Categories: C# Code
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: