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?
Garbage collection is performed on objects, not on variables.
output
is not garbage collected; theHashSet
you created (which had a reference temporarily stored inoutput
) 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).