Search code examples
c#objectclone

Object cloning in c#


Consider this related question: Deep cloning objects

Is this really the best way to clone an object? (serialize/deserialize). Serialization seems a bit expensive to me.

My idea was to create a second constructor and just assign all variables. Would this approach be faster?

class Test
{

public Test(Test clone)
{
// clone ....
}
}

Solution

  • If you are talking about using a custom class, the best way is to implement ICloneable. This way your class can provide a standardized way to clone itself.

    There are some times when using a 'copy constructor' can be better, but usually only if you can see that it would be simple, and ICloneable doesn't meet your needs adequately.