Click here to Skip to main content
15,892,643 members
Articles / Programming Languages / C#

Object Cloning at its simplest

Rate me:
Please Sign up or sign in to vote.
2.55/5 (8 votes)
28 Feb 2008CDDL1 min read 42.7K   342   12  
A reusable static class to clone objects, not specific to TYPE of the object
using System;
using System.Collections.Generic;
using System.Text;

namespace CloneExample
{
    [Serializable]
    class ExampleClass1
    {
        public int a;
        string b;
        double c;
        public ExampleClass1()
        {
            a = 1;
            b = "abc";
            c = 0.1;
        }
        public override string ToString()
        {
            string ret = "Example1\nValues=>" + a.ToString() + ", " + b + ", " + c.ToString();
            return ret;
        }
    }

    [Serializable]
    class ExampleClass2
    {
        ExampleClass1 ex1;
        string name;
        public ExampleClass2()
        {
            ex1 = new ExampleClass1();
            name = "Rahul";
        }
        public override string ToString()
        {
            string ret = "\nExample2\nMy name is " + name + "\nValues=>" + ex1.ToString();
            return ret;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass1 e1 = new ExampleClass1();
            ExampleClass1 e2;
            ExampleClass2 e3 = new ExampleClass2();
            ExampleClass2 e4;

            e2 = ObjectClone.Clone<ExampleClass1>(e1);
            e4 = ObjectClone.Clone<ExampleClass2>(e3);

            e2.a = 23;

            Console.WriteLine(e1.ToString());
            Console.WriteLine(e2.ToString());
            Console.WriteLine(e3.ToString());
            Console.WriteLine(e4.ToString());
            Console.ReadLine();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


Written By
Technical Lead
India India
Acquired Degree of Bachelor in 2007 from Pune University, in VP College Of Engg., Baramati. There on worked in organisations to design and implement web based software applications.

Comments and Discussions