Useful Extension Method for ICloneable

Posted by DesigningCode on Geeks with Blogs See other posts from Geeks with Blogs or by DesigningCode
Published on Fri, 07 May 2010 02:02:13 GMT Indexed on 2010/05/11 2:55 UTC
Read the original article Hit count: 305

Filed under:

 

In the past, I’ve had to put a type specific clone in each cloneable class, but with extension methods you can write a generic T specific clone

class Program
    {
        static void Main(string[] args)
        {
            var b = new Blah() {X = 1, Y = 2};
            var bb = b.Clone();
            Console.WriteLine(string.Format("{0} {1}", bb.X, bb.Y));
        }
    }
    
    public class Blah : ICloneable
    {
        public int X;
        public int Y;
        object ICloneable.Clone()
        {
            return MemberwiseClone();
        }
    }
    public static class CloneExtension
    {
        public static T Clone<T>(this T o) where T : ICloneable 
        {
            return (T)o.Clone();
        }
    }

© Geeks with Blogs or respective owner