#190 – Memory Management for Heap-Based Objects

In C#, you create an object on the heap when you instantiate an object using the new keyword.

            Person general = new Person("Julius", "Caesar");

We now have a Person object on the heap and a reference to that object–the variable general.

We can also declare a second variable that references the same object.

            Person antonysFriend = general;

Now we have one Person object on the heap and two references to it.

The memory for an object on the heap can be freed when it’s no longer being referenced by any variables.  This can happen when the variables that reference it go out of scope, or when they are set to point to another object.

More precisely, the memory will be reclaimed by the Garbage Collector (GC) in .NET.  When an application needs more memory, the GC is triggered and it releases memory for any dead objects.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #190 – Memory Management for Heap-Based Objects

  1. Pingback: #921 – Objects Are Explicitly Created but Automatically Destroyed | 2,000 Things You Should Know About C#

  2. Pingback: #924 – You Shouldn’t Normally Worry about Memory Management | 2,000 Things You Should Know About C#

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: