#938 – Finding Out What GC Generation an Object Is In

The garbage collector (GC) groups objects into generations to avoid having to examine and collect all objects in memory whenever a garbage collection is done.

For debugging purposes, it’s sometimes useful to know which generation an object currently belongs to.  You can get this information using the GC.GetGeneration method, as shown below.

            Dog bob = new Dog("Bob", 5);
            Console.WriteLine(string.Format("Bob is in generation {0}", GC.GetGeneration(bob)));

            GC.Collect();
            Console.WriteLine(string.Format("Bob is in generation {0}", GC.GetGeneration(bob)));

            GC.Collect();
            Console.WriteLine(string.Format("Bob is in generation {0}", GC.GetGeneration(bob)));

In the example above, the “Bob” Dog object starts out in generation 0. After we do the first garbage collection, it’s promoted to generation 1 and after the 2nd collection, it’s promoted to generation 2.
938-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #938 – Finding Out What GC Generation an Object Is In

  1. Pingback: Dew Drop – September 25, 2013 (#1,631) | Morning Dew

  2. Nice one to know 🙂 Thanks Sean for your great articles!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: