views:

229

answers:

4

Possible Duplicate:
Cloning objects in C#

I have this class Object that has about 20 properties (they're all basic or struct types). Is there a simple way to create a clone of an instance of this object. A bit like the copy ctor in C++?

This is for a Silverlight application.

+2  A: 

Object.MemberwiseClone is an option. Note that this will create a shallow clone. If you have reference types in the object, you will copy the reference. If you only have value types (and optionally strings and other immutable objects) in the class, you will be safe using MemberwiseClone.

driis
+4  A: 
Object.MemberwiseClone();

will give you a Shallow Copy. If you need anything more complex, you probably want to look into the ICloneable interface.

Justin Niessner
+6  A: 

I think this answers your question.

Farinha
+2  A: 

As others suggested the most likely answer you want is Object.MemberWiseClone() (vote them up, not me.)

However, if the following caveat is a concern to you, you may want to just write your own copy-constructor in C#.

If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

class Foo
{
    public Foo()
    {
        this.MyInt = 99;
        this.MyString = "Hello, World";
    }

    // This copy constructor can be as deep or shallow as you want,
    // and can instantiate new instances of any of source's
    // reference-type properties if you don't want both Foo's to refer
    // to the same references. (MyBar, in this elementary example).
    public Foo(Foo source)
    {
        this.MyInt = source.MyInt;
        this.MyString = source.MyString;
        // For example, using another copy constructor.
        this.MyBar = new Bar(source.MyBar);
    }

    public int MyInt { get; set; }
    public string MyString { get; set; }
    public Bar MyBar { get; set; }
}

class Bar
{
    public Bar(Bar source)
    {
    }
    // ...
}

Of course, that copy constructor can be as simple or as complex as you need.

JMD