Overly Excessive
Overly Excessive

Reputation: 2125

Need some clarification regarding reference types

So I'm reading an article by Jon Skeet regarding parametering passing in C# and he's made the following example to explain how reference types work, but I can't wrap my head around it.

StringBuilder first = new StringBuilder();
first.Append("hello"); 
StringBuilder second = first;
first.Append(" world");
first = new StringBuilder("goodbye");
Console.WriteLine(first); // Prints goodbye
Console.WriteLine(second); // Still prints hello world

When we're assigning the value of the second variable are we just setting that value to the reference of the StringBuilder object?

Also as a bonus question, if we would change the reference of the second variable to something else(setting it to a null value for example), would the reference to the first StringBuilder object then be irretrievable? Or is there any way to retrieve all created objects of a certain type?

Upvotes: 1

Views: 66

Answers (3)

Omri Aharon
Omri Aharon

Reputation: 17064

StringBuilder second = first;

means that the second variable now holds the reference to the same place in the memory as first variable.

However, this line:

first = new StringBuilder("goodbye");

Now says that first gets a brand new reference to a new object, thus breaking the connection between first and second.

Upvotes: 1

Tigran
Tigran

Reputation: 62246

When we're assigning the value of the second variable are we just setting that value to the reference of the StringBuilder object?

Yes. We just copy a pointer to the memory that contains "hello world".

if we would change the reference of the second variable to something else, would the reference to the first StringBuilder object then be irretrievable? Or is there any way to retrieve all created objects of a certain type?

Yes, and the memory allocated by it, will become a candidate for garbage collection as there is no any pointer referencing to it.

Upvotes: 3

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Line

first = new StringBuilder("goodbye");

breaks the connection between those two objects.

So first has goodbye and second has hello world

Upvotes: 0

Related Questions