Set it equal to the value, not the address

Ok so I have two objects of the same type:

//C#

myObject Ob1 = new myObject();

myObject Ob2 = new myObject();

And when I do this:

Ob1 = Ob2;

It makes Ob1 point to what Ob2 points to, but I don't want that, I want to copy the value of what Ob2 points to into what Ob1 points to, basically I want to do this:

//C++

//I want this:

*Ob1 = *Ob2;

//not this:

Ob1 = &*Ob2;

//or this:

Ob1 = &Ob2;

I would appreciate it if some one could help me out.



Answer this question

Set it equal to the value, not the address

  • mf915

    Well, imagine that you have an object that contains references to another object, as well as, say, an integer value.

    If you copy the object so that the integer and the reference is copied, it is a shallow copy. (The reference still points to the same object that it did before.)

    If you copy the object so that the integer is copied, and a new object is created for the referenced object, and the copied object is made to refer to that new object, it is a deep copy. (The reference now points to a COPY of the object that it previously pointed to.)




  • Francis Shanahan

    I think I am going to make a cloning class using C++ and C++/CLI.
  • chinmayv84

    Just remember that you will face the same issue: Will you do a deep or shallow copy

  • David Ruiz

    An Object has no value, it's merely a reference. If you want to make a copy of the contents (value) of an object, that object must implement something that supports copying (either shallow or deep). One way is to test if the object supports ICloneable:

    MyObject o1 = new MyObject();
    MyObject o2 = null;
    ICloneable cloneable = o1 as ICloneable;
    if(cloneable != null)
    {
    o2 = cloneable.Clone();
    }

    If you're always dealing with a MyObject instance and it implements ICloneable and it's not implemented as an explicit interface implementation, then you can skip the cast to an ICloneable object and just do the following:

    MyObject o2 = o1.Clone();

    Either way, the class itself has to implement something to copy the value(s) of the object; only it knows how to do that.

  • Bruce Baker

    ya I alread gave up on that, I was thinking I was going to pass some objects to native C++ and do:

    *object1 = *object2;

    but you can't do that operation on a managed handle, and there is no way (I know of) to convert a managed class to a native class, so there doesn't seem to be any way to make a generic cloning procedure for managed classes 

    just out of curousity, what is the diffrence between a shalow and deep copy


  • Set it equal to the value, not the address