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.
1
2
3
4
5
6
| 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.

