Rohan
Rohan

Reputation: 359

Is my object copied memory or a pointer to the original object's memory?

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.

Upvotes: 0

Views: 331

Answers (2)

tdelepine
tdelepine

Reputation: 2016

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

Upvotes: 1

Dave Zych
Dave Zych

Reputation: 21897

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.

Upvotes: 2

Related Questions