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.
source to share
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.
source to share
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"
source to share
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.
source to share