#227 – Instances of Classes Are Created on the Heap

Because they are reference types, instances of classes are stored on the heap.  When you instantiate (or create) an instance of a class, the actual object is created on the heap and you reference the newly created object with a variable whose type corresponds to the class’ type.  The variable that references the object is stored on the stack.

            // New Person object created on the heap
            // p variable is a stack-based reference to the new object
            Person p = new Person("Cary", "Grant");

Because a class object is created on the heap, you don’t destroy the object explicitly, but it is automatically garbage collected.  The object will be a candidate for garbage collection when there are no longer any variables that reference the object.

            p = new Person("Jimmy", "Stewart");

            // No variable references Cary Grant anymore,
            // so he can be garbage-collected.
Advertisement

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

One Response to #227 – Instances of Classes Are Created on the Heap

  1. Pingback: #666 – Looking at .NET Memory Usage Using Performance Counters « 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 )

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: