web 2.0

Creates a shallow copy of any Objects with Generic Extension Method

Hi !

In this article I'll give you a useful Extension Method in order to create a shallow copy of any objects by calling Object.MemberwiseClone Method.

The following Extension is useful to Clone Objects without inherits them with IClonable interface.

 

Here is the Extension Code

public static T Clone<T>(this T o) where T : class
{
    Type type = o.GetType().BaseType;

    MethodInfo[] methodInfos = type.GetMethods(BindingFlags.NonPublic
                    | BindingFlags.Instance
                    | BindingFlags.DeclaredOnly);
    MethodInfo cloneMethod = null;
    foreach (var item in methodInfos)
    {
        if (item.Name == "MemberwiseClone")
        {
            cloneMethod = item;
            break;
        }
    }
    if (cloneMethod != null)
    {
        return (T)cloneMethod.Invoke(o, null);
    }
    return default(T);
}

Here is a sample of usage

public class Test
{
    public String Name { get; set; }
}

Test obj1 = new Test() { Name = "Blah" };
Console.WriteLine(obj1.Name);

Test obj2 = obj1.Clone<Test>();
Console.WriteLine(obj2.Name);

 

Hope this help's

NB : I think this Extension can be improved, but it's a begining.



Views(1044)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile