Reputation: 2269
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?
Upvotes: 6
Views: 189
Reputation: 37770
While there's an answer, which solves OP problem, I'll add another one, which answers the question. To get instance of class without executing its constructor, use FormatterServices.GetUninitializedObject:
var uninitializedObject = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));
Upvotes: 3
Reputation: 17185
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.
Upvotes: 8