Reputation: 143
Below is code snippet in which I am getting generation of variable int j
before and after calling garbage collector.
int j = 30;
WriteLine(GC.GetGeneration(j) );
GC.Collect();
WriteLine(GC.GetGeneration(j));
The output should be
0
1
as int j
is surviving garbage collection But I am getting
0
0
I don't understand why this is happening because int
is also an object in C#.
PS: I have tried running project in debug as well as in release mode.
Upvotes: 1
Views: 241
Reputation: 36361
As mentioned in the comments. an int
is a value type and is not tracked by the garbage collector. Since GetGeneration
takes an object
, the int will be boxed. I.e. a new object will be created. That new object will always be allocated in gen 0. The next time you call GetGeneration
the same thing will occur.
So your results are as expected.
Upvotes: 6