Yes, it is possible with the method GC.GetGeneration()
.
The practical usefulness in normal code is debatable. You can’t even make much use of it because it’s implementation detail. It is useful for making diagnostics, measurements, experiments and perhaps something very advanced, probably a development tool more than a normal application.
What you need to know is that the ideal is that objects die young or live forever, you don’t need to know what generation he’s in. When we say you must prevent an object from reaching Gen2, it doesn’t mean you have to keep monitoring it. The problem with Gen2 is that if it has to be collected it can take a very long pause.
using System;
public class Program {
public static void Main() {
var objeto = new object();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
GC.Collect();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
GC.Collect();
Console.WriteLine($"Geração {GC.GetGeneration(objeto)}");
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
You mean where he is in memory? I never needed to know that until today.
– PauloHDSousa
@Paulohdsousa No, I refer to the "generations" of the GC. Perhaps the question becomes clearer if you take this my other question.
– nmindz