#199 – You Can’t Explicitly Delete Heap-Based Objects

You create a new instance of a reference type by using the new operator and declaring a reference to the new object.  Memory for the object is allocated on the heap and the reference to the object is stored on the stack.

The object itself is able to be destroyed, i.e. its memory freed, when there are no longer any variables that reference it.  This is done automatically by the Garbage Collector (GC) in .NET.

Unlike with C++, you cannot explicitly delete a heap-based object and free its memory.  Only the Garbage Collector can release the memory for the object.  The Garbage Collector will not actually destroy the object unless a) there are no longer any references to the object and b) the CLR invokes the Garbage Collector because it needs memory.

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.

4 Responses to #199 – You Can’t Explicitly Delete Heap-Based Objects

  1. Pingback: #201 – You Can Leak Memory in C# « 2,000 Things You Should Know About C#

  2. Pingback: #227 – Instances of Classes Are Created on the Heap « 2,000 Things You Should Know About C#

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

  4. Pingback: #923 – An Object Isn’t Necessarily Deleted as Soon as Its Dereferenced | 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: