0

Sorry if the question seems weird, I didn't know how to really put this. Therefore, I'm not sure if this question has been asked before.

Take this piece of code:

    Object obj = new Object();

    Object obj2;

    obj2 = obj;

So my question is:

When I assign obj to obj2, is obj2 pointing to obj's memory, or is the runtime allocating a new chunk of memory that is identical to obj's memory?

Thanks, Ro.

2 Answers 2

2

obj2 has a reference to the same object that obj points to. Since they are pointing to the same object, modifications to obj2 are "reflected" in obj.

0
1

Here is a simple example to illustrate that it is a reference and not a copy

 public class ClassObject
    {
        public int entier;

        public ClassObject(int p_Initial)
        {
            this.entier = p_Initial;
        }
    }



        ClassObject obj1 = new ClassObject(2);
        Console.WriteLine(obj1.entier); ==> Console obj1.entier = 2
        ClassObject obj2 = obj1;
        obj2.entier = 5;

        Console.WriteLine(obj1.entier); ==> Console obj1.entier = 5
        Console.WriteLine(obj2.entier); ==> Console obj2.entier = 5
1
  • If you want create a copy of an object in C# you can use an implementation of ICloneable Interface du namespace System.Object
    – tdelepine
    Sep 4, 2013 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.