Static class variables not reached in Finalize?

  • Thread starter Thread starter MuZZy
  • Start date Start date
M

MuZZy

Hi,
Consider i have a class:

class CTest
{
public static int Counter = 0;
public CTest()
{
<...>
Counter ++;
}
public override Finalize()
{
Counter --;
<...>
}
}

I found that if creating objects of this class at some point in the winforms app, and then "nulling"
the object variables, Finalize is at some point called by GC, but value of Counter never goes down,
meaning that Counter-- never in fact occures - if i aqucuire CTest.Counter at any time from the app,
it shows the number of created objects, never decreasing as the objects get collected by GC.

Is it a normal behaviour? Are the static class variables not accessibe from Finalize method?

Thank you,
Andrey
 
first, the code you supplied is not even valid C#.

and how do you know GC actually ran? did you force it? because garbage
collection is indeterministic, so just by having objects falling out of scope
doesn't guaranttee you it's immediately collected.

here's a sample to demostrate that it definitely works.

public class MyClass
{

private static int count;

public MyClass()
{
count++;
}

~MyClass()
{
count--;
}

public static void Main()
{

MyClass a = new MyClass();

Console.WriteLine( count );

MyClass b = new MyClass();

Console.WriteLine( count );

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine( count );

Console.ReadLine();
}
}
 
As Daniel pointed out, the Finialize code may not be called when you
think. In fact, it may NEVER be called!

The best solution is to implement the IDisposable interface and to call
the .Dispose method on your objects

Chris
 
Chris said:
As Daniel pointed out, the Finialize code may not be called when you
think. In fact, it may NEVER be called!

The best solution is to implement the IDisposable interface and to call
the .Dispose method on your objects

Chris


Well, i had a c++ code but kinda mesed up with "Finalize" when converting it to C# here in the post.
Yeap, i ran Daniel's code and it proves that finalize correctly treats static class variables.
So now i know that if the counter doesn't decrease in my case, i have a problem with that class.

Thank you both for the replies!

Andrey
 
Back
Top