Reputation: 415
Is it necessary to do this poly = null; ? After finishing the function the Garbage Collector would clean up or ?
Here a simple example:
public void redrawSingelPoly(Canvas canvas)
{
Polyline poly = new Polyline();
poly.Stroke = colorBrush;
poly.StrokeThickness = basicLineThick;
poly.Points = points;
canvas.Children.Add(poly);
poly = null; //Garbage Collector
}
Upvotes: 2
Views: 382
Reputation: 4636
Your poly object will NOT be garbage collected in your example. Here is why...
You are doing the following...
canvas.Children.Add(poly);
Which keeps a reference to the object. Even though you set your local reference to that object = null, there is still a reference to it that is passed out of the method!
The garbage collector only collects unreacheable objects.
That being said - Is it necessary to set poly = null? No it is not necessary.
Upvotes: 6
Reputation: 30912
Setting poly
to null
is unnecessary, at least for two reasons.
Since C# (and .net in general) is a managed memory environment, the memory for the variable will be done with automagically, by the garbage collector.
The garbage collector will not collect memory that is still in use, and if the canvas.Children
property is in scope, so will be the memory used by the Polyline
object, regardless of the value of the poly
variable.
Upvotes: 1
Reputation: 62265
In general it's not necesssary, but what warries me is :
canvas.Children.Add(poly);
this line. Not very clear what happens inside Add(..)
method.
From the scope perspective GC
will locate and collect all local variables that are not referenced by global refrences, so there is no sence of doing =null
Upvotes: 0