-2

I have an object with a number of private properties. It has an empty constructor, and a constructor that accepts an instantiated version of itself. I need to assign this new instance to a deep copy of the old instance. Can this be done? Example:

public class Foo
{
    private Property p;

    public Foo()
    {
        p = new Property("this and that");
    }
        public Foo(Foo f)
    {
        this.Object = f.DeepCopy;   // What would this statement be?
    }
}

Halp.

icedwater
  • 4,701
  • 3
  • 35
  • 50

1 Answers1

0

you can use the below method for deep copying of object from one to other.

public T DeepCloneTheObject<T>(T obj)
        {
            using (var ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Position = 0;

                return (T)formatter.Deserialize(ms);
            }
        }

In your example, you can say, DeepCloneTheObject(f)

G_S
  • 7,068
  • 2
  • 21
  • 51
  • Thanks for the reply, but how would I assign it to the current object? I need to make all the properties of the instance equal the properties of the clone. The only thing I can think of is something along the lines of "this.Object = DeepCloneTheObject(f);". – crapolantern Feb 12 '18 at 18:09
  • Yes doing that should work – G_S Feb 12 '18 at 18:10