Link types. Am I understanding this correctly?

This is embarrassing. I have studied C # for a long time and now I am trying to understand this question about classes (these are reference types of course).

Here's the question: if I create two new instances of a class named Person

and named one instance P

and the other Q

(who cares why I would name it Q

) and set P.Name

before "James"

and then set Q.Name

to "Suzie"

, will it get P.Name

set "Suzie"

? Or am I not getting it right?

Thanks everyone

Thank you all for helping me with this. I assumed I had it explained. But the explanations in the tutorials I read were incomprehensible and I didn't have a computer in months to test it myself.

Ps I chose the first correct answer that I understood. But I noticed a few. Thanks again for your help.

+3


source to share


5 answers


The short answer is NO, changing the Q.Name will not affect P.Name. As in

 var p = new Person();
 var q = new Person();
 p.Name = "James";
 q.Name = "Suzie";

      

However, if q points to a p instance, then changing q will also change p. How in:

 var p = new Person();
 var q = p;
 p.Name = "James";
 q.Name = "Suzie";

      



Both q and q Name are now "Suzie".

With data initializers, you can write the first example as:

var p = new Person { Name = "James" };
var q = new Person { Name = "Suzie" };

      

which I think is much easier to read.

+5


source


Example:



// p and q are separate in the below example..

Person p = new Person();
Person q = new Person();

p.Name = "James";
q.Name = "Suzie";

Console.WriteLine(p.Name); // "James"
Console.WriteLine(q.Name); // "Suzie"

// both p and q refer to the same object, so both are "Suzie" in the below example
Person p = new Person();
Person q = p;

p.Name = "James";
q.Name = "Suzie";

Console.WriteLine(p.Name); // "Suzie"
Console.WriteLine(q.Name); // "Suzie"

      

+3


source


No, it is not, because both P and Q differ in an instance of the Person class . Both objects or instances are defined in different memory locations. see this tutorial

+3


source


Should you create two instances? No, they will be two separate entities.

Person person1 = new Person();
person1.Name = "James";
Person person2 = new Person();
person2.Name = "Suzie";
Console.WriteLine(person1.Name);
Console.WriteLine(person2.Name);

      

This will print James

, then Suzie

, since they are two different objects. If you did this, however:

Person person1 = new Person();
person1.Name = "James";
Person person2 = person1;
person2.Name = "Suzie";
Console.WriteLine(person1.Name);
Console.WriteLine(person2.Name);

      

This will print Suzie

and Suzie

. This is due to the fact that they person1

both person2

refer to the same object.

+2


source


This will not change P.Name to Suzie, since you created two instances of the same class, which means that you have allocated two different memory locations on the heap for those two instances .

+1


source







All Articles