Reputation: 1
When an object is returned by a method, it remains in existence until there are no more references to it. At that point, it is subject to garbage collection. Thus, an object won’t be destroyed just because the method that created it terminates.
Upvotes: 0
Views: 254
Reputation: 113292
If you have:
string Method1()
{
return new Random().Next(0, 1000).ToString();
}
Then when you call it, it creates a Random
object, and soon afterwards a string
object.
Once the method is done using the Random
object by calling Next
(note, whether the method has returned or not has absolutely nothing to do with this, regardless of what that book might say). there's no more references to it anywhere that any code will reach it by, so it might be collected.
If though the string was obtained in:
void Method2()
{
string s = Method1();
//s isn't collected here by devious forces.
Console.WriteLine(s);//this works.
}
So the book is saying "things don't magically disappear when you use them.
It's actually incorrect, in:
void Method3()
{
Method1();
}
There's no reason to suspect that the string wasn't collected before the method method returned.
But also:
static string blah
void Method4()
{
blah = new Random().Next(0, 10).ToString();
}
This didn't return anything, but it created an object that won't be collected.
Also:
void Method5(out string ret)
{
ret = new Random().Next(0, 10).ToString();
}
void Method 6()
{
string s;
Method5(out s);
//s isn't collected here by devious forces.
Console.WriteLine(s);//this works.
}
Here's a better version:
"Once there is no way that any code which will run could use the object, it may be collected."
Buy a better book, there's no point asking people to explain what Herbert Schildt says about something, because that assumes he's correct. Frankly, I'd be more worried about the bits you thought you understood than the bits you were confused by, because you won't know if it was actually correct or bullschildt.
Upvotes: 0
Reputation: 102763
It means that in the scenario below, after you call Run()
, a
will not be garbage collected, even though it's a private object. That's because _b
exists outside the scope of the method, and still holds a reference to a
.
class Test
{
private B _b;
public void Run()
{
A a = new A();
_b = new B(a);
}
}
public class A
{
}
public class B
{
private A _a;
public B(A a)
{
_a = a;
}
}
Upvotes: 1