The method does not need to be populated, but you also do not need to set the variable to null if the GC can say that you are not going to read it again. For instance:
public void Foo()
{
SomeObject x = new SomeObject();
Console.WriteLine("Eligible for collection");
}
- , , . , - . , , GC , , GC. :
using System;
class Bomb
{
readonly string name;
public Bomb(string name)
{
this.name = name;
}
~Bomb()
{
Console.WriteLine(name + " - going boom!");
}
public override string ToString()
{
return name;
}
}
class Test
{
static void Main()
{
Bomb b = new Bomb("First bomb");
Console.WriteLine("Using bomb...");
Console.WriteLine(b);
Console.WriteLine("Not using it any more");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Creating second bomb...");
b = new Bomb("Second bomb");
Console.WriteLine("Using second bomb...");
Console.WriteLine(b);
Console.WriteLine("End of main");
}
}
:
Using bomb...
First bomb
Not using it any more
First bomb - going boom!
Creating second bomb...
Using second bomb...
Second bomb
End of main
Second bomb - going boom!
, : , " ", GC , . , :
using System;
class Bomb
{
int x = 10;
~Bomb()
{
Console.WriteLine("Boom!");
}
public void GoBang()
{
Console.WriteLine("Start of GoBang");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("x={0}", x);
Console.WriteLine("No more reads of x");
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Returning");
}
}
class Test
{
static void Main()
{
Bomb b = new Bomb();
b.GoBang();
Console.WriteLine("Still in Main");
}
}
:
Start of GoBang
x=10
No more reads of x
Boom!
Returning
Still in Main
( - , .)
: null... . null. .