#201 – You Can Leak Memory in C#

In C#, you don’t need to explicitly free memory allocated by creating objects on the heap.  The objects will be automatically garbage collected when no longer referenced.  This means that you won’t experience memory leaks due to forgetting to delete an object.

You can, however, still leak memory in C#.  This can happen if you create one or more new objects on the heap and refer to them from a variable that never goes out of scope during the application’s lifetime.

        public static List<Person> userLog;

        static void RecordUserInfo(Person justLoggedIn)
        {
            userLog.Add(justLoggedIn);
        }

Here we’re adding to a list of Person objects whenever the RecordUserInfo method is called (presumably when someone logs in).  Assuming that we never remove someone from this list, none of the Person objects added to the list will ever get garbage collected–because we’ll continue to reference them indefinitely.  We’re leaking memory.

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.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers