user2261524
user2261524

Reputation: 415

C#: Garbage collector

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

Answers (3)

Kevin
Kevin

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

SWeko
SWeko

Reputation: 30912

Setting poly to null is unnecessary, at least for two reasons.

  1. 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.

  2. 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

Tigran
Tigran

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

Related Questions