Home > Development > Cloning Entities in .NET

Cloning Entities in .NET


using System;

namespace CloningExamples
{

    public class Point
    {
        private readonly int _x;
        private readonly int _y;

        public Point(int x, int y)
        {
            this._x = x;
            this._y = y;
        }

        public int X
        {
            get { return _x; }
        }

        public int Y
        {
            get { return _y; }
        }
    }

    public class Point2 : ICloneable
    {
        private readonly int _x;
        private readonly int _y;

        public Point2(int x, int y)
        {
            this._x = x;
            this._y = y;
        }

        public int X
        {
            get { return _x; }
        }

        public int Y
        {
            get { return _y; }
        }

        public object Clone()
        {
            return new Point2(X, Y);
        }
    }

    public static class CloneableExtensions
    {
        public static T CloneObject(this T entity) where T : ICloneable
        {
            return (T) entity.Clone();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point p1 = new Point(1,2);
           // There is no clone method by default -- Point p2 = p1.Clone();
            Point2 p2 = new Point2(10,20);
            Point2 p3 = (Point2) p2.Clone();
            Point2 p4 = p2.CloneObject();

            Console.WriteLine(p4.X + " " + p4.Y);
            Console.ReadKey();
        }
    }
}

Blair

Advertisements
Categories: Development Tags: , , , ,
  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: