Reference Types Copying and Garbage Collector

345 views Asked by At

I have the following function:

HashSet<string> Func()
{
     HashSet<string> output = new HashSet<string>();
     output.Add("string_1");
     output.Add("string_2");
     return output;
}

Then I call this method and copy it to a reference type:

HashSet<string> bindingObjct = Func();

This is reference copying from the return of the function "output" and the binding variable at call "bindingObjct", so both are referring to the same objects.

My question: When garbage collector is made on "output" (the local variable inside the function), will this affects "bindingObject"? even while using "bindingObject" recently?

2

There are 2 answers

1
Chris Hayes On

Garbage collection is performed on objects, not on variables. output is not garbage collected; the HashSet you created (which had a reference temporarily stored in output) will be garbage collected at some point after no live variables store references to it.

In short, the variables you're referring to will not be changed in any way. The HashSet remains valid for its lifetime. Once it's eligible for garbage collection you will no longer be able to access it (by definition; if you were able to access it, it wouldn't be eligible for garbage collection).

0
Dave On

The GC will only collect objects that are no longer referenced anywhere - it's fairly pessimistic by default. If you have several references to the same object the .NET GC will handle this, but tracking the life of the object and graph can become a factor in performance.

So by my understanding the answer to your question is 'No', the GC will not act on an object that is referenced elsewhere