0

Consider a simple class A below :

class A 
{
    public static int b = 10;
}


  {
    var objA = new A();
    A.b = 30;
    Console.WriteLine("Before GC Collect!");
    Console.WriteLine(A.b);

    objA = null; 
    GC.Collect();  //A is GC Collected

    var objB = new A(); 
    Console.WriteLine("After GC Collect!");
    Console.WriteLine(A.b);
  }

Note: The member b is static

I expected an answer of 30 before GC collection and 10 after GC Collection

When a object is GC Collected, does it mean that all the static instances associated with that class are not destroyed ?

Why so ? Any ideas ?

  • How would the GC know that you've stopped using the public static class A? The GC can only know that you no longer hold references to a particular *instance* of a class. You still have access to A.b at all times. – Steve Lillis Dec 10 '14 at 09:30
  • For code in normal assemblies only instances can be collected, never classes. There is a special assembly type called [Collectible Assemblies](http://msdn.microsoft.com/en-us/library/dd554932.aspx) which can be collected including the classes, but these are special purpose and probably not what you're interested in. – CodesInChaos Dec 10 '14 at 09:44

1 Answers1

3

When an instance of a class is removed, all instance members in that instance are removed.

When one instance of a class is removed, all other instances of that class are unaffected.

Static members of a class are independent of instances of the class. A static member of a class exists once in the application, regardless of how many instances there are of the class. The static members exist before there are any instances at all, and are still there after all instances are gone.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005