Geeks With Blogs
Keith Nicholas

 

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();
        }
    }
Posted on Friday, May 7, 2010 3:02 PM | Back to top


Comments on this post: Useful Extension Method for ICloneable

# re: Useful Extension Method for ICloneable
Requesting Gravatar...
Why are you casting o to T?

return (T)o.Clone();

o is already of type T.
Left by Pieter on May 11, 2010 7:53 PM

# re: Useful Extension Method for ICloneable
Requesting Gravatar...
Generics is really a very powerful feature its provide a type safety and showing run time error on compile time.i am a java developer and i think many features of C# is copied from java.
Left by Texas Breeder Bucks on Jun 03, 2010 7:46 PM

Your comment:
 (will show your gravatar)


Copyright © DesigningCode | Powered by: GeeksWithBlogs.net