Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make clone of class instance?

So I have this class:

class Test
{
    private int field1;
    private int field2;

    public Test()
    {
        field1 = // some code that needs
        field2 = // a lot of cpu time
    }

    private Test GetClone()
    {
        Test clone = // what do i have to write there to get Test instance
                     // without executing Test class' constructor that takes
                     // a lot of cpu time?
        clone.field1 = field1;
        clone.field2 = field2;
        return clone;
    }
}

The code pretty much explains itself. I tried to solve that and came up with this:

private Test(bool qwerty) {}

private Test GetClone()
{
    Test clone = new Test(true);
    clone.field1 = field1;
    clone.field2 = field2;
    return clone;
}

I havent tested it out though, but am I doing it right? Is there better way to do that?

like image 609
foxneSs Avatar asked Feb 01 '14 14:02

foxneSs


1 Answers

Normally, one would write a copy constructor for this:

public Test(Test other)
{
     field1 = other.field1;
     field2 = other.field2;
}

If you want, you can also add a Clone method now:

public Test Clone()
{
     return new Test(this);
}

Going even further, you could have your class implement ICloneable. This is the default interface a class should implement if it supports cloning of itself.

like image 57
PMF Avatar answered Oct 15 '22 04:10

PMF