Sam
Sam

Reputation: 3160

Referencing an object in c#

I have a class called node. I want to store each nodes parent within each node like this:

public class Node
{
    public Node parent;
}

So say I assign parent to a node:

Node n = new Node();
Node n2 = new Node();
n.parent = n2;

If I change n2, will the parent variable of n change too?

Upvotes: 1

Views: 2491

Answers (6)

supercat
supercat

Reputation: 81115

Think of variables, parameters, array slots, etc. of class types as holding "object IDs". A statement like n1.parent = n2; says "Find the object identified by the object ID stored in n1, which will be of type Node; change the parent field of that object to contain the object ID stored in n2".

Suppose n1 was initially assigned [Object ID#1] and n2 was initially assigned [Object ID#2]. The statement n1.parent = n2 will make the parent field of the Object #1 contain [Object ID #2]. If one were to perform a statement like n2.someProperty = 5 before one stores anything else in n2, that statement would modify that property of Object #2. Since the parent field of Object #1 holds [Object ID#2], the statement would also appear to modify n1.parent.someProperty. On the other hand, if one were to store a different object ID into n2, that would have no effect on n1.parent, which would continue to hold [Object ID #2].

Upvotes: 1

Vlad
Vlad

Reputation: 2565

public class Node
{
   public string a;
   public Node parent;
}

Node n = new Node();

Node n2 = new Node();
n2.a = "1";
n.parent = n2; 

// n.parent.a is "1" now

n2.a = "2";

// n.parent.a is "2" now

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

No, the parent variable of n will not change: once a reference is copied, it gets a life of its own. If you change the Node pointed by n2, however, n's parent will see that change. For example, if you set n2.parent = n3, n.parent.parent will change to n3 as well.

Upvotes: 4

shipr
shipr

Reputation: 2839

Yes, you refer to the same object by reference.

Upvotes: 0

AD.Net
AD.Net

Reputation: 13399

Yes, that's by reference, n.parent = n2;

To be clear, if you change N2 (ie. N2.prop = newvalue), when you do n.Parent.prop, it'll be the newvalue.

Upvotes: 1

The Internet
The Internet

Reputation: 8103

Yes, since it is by reference. It will be updated in both n and n2

Upvotes: 0

Related Questions