Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, that will <em>not</em> cause a memory leak. The code you wrote is just fine. The thing you have to remember about C# (and the other .NET languages) is that they are <strong>garbage collected</strong>.</p> <p>Unlike C++, where you are explicitly responsible for creating and freeing memory yourself, that's not the case in the managed world of .NET. All you have to worry about is <em>creating</em> the object. When there are no longer any remaining references to it, it becomes eligible for garbage collection. Seriously, I know this sounds weird, given your background in other languages, but you really should just let the garbage collector worry about such things. The "correct way of thinking about such situations" is indeed not to think about them at all!</p> <p>In fact, the <em>only</em> time that you need to write a destructor (and thus worry about memory management) is if your class makes use of unmanaged objects (such as window handles, GDI+ objects, etc.) or other objects that require explicit closing (file handles, database connections, etc.). In the .NET world, you want to write a destructor as <em>rarely</em> as possible, because there's a slight performance penalty in doing so. The specifics lie in the implementation of the garbage collection algorithm, and at what point the object can be collected, but you shouldn't try to learn all that. </p> <p>The important thing to remember is that if you do need to "clean up" when the object gets destroyed, you should implement the <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow"><code>IDisposable</code> interface</a>, like many of the WinForms classes (e.g. <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx" rel="nofollow"><code>Control</code></a>) do that use unmanaged objects internally.</p> <p>Here are a couple of good resources for learning more about .NET's garbage collection model:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx" rel="nofollow">Garbage Collection</a> on MSDN</li> <li><a href="http://msdn.microsoft.com/en-us/library/ms973837.aspx" rel="nofollow">Garbage Collector Basics and Performance Hints</a> by Rico Mariani</li> <li><a href="http://msdn.microsoft.com/en-us/magazine/bb985010.aspx" rel="nofollow">Garbage Collection: Automatic Memory Management in the MS .NET Framework</a> by Jeffrey Richter</li> <li><a href="http://www.simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/" rel="nofollow">Understanding Garbage Collection in .NET</a> by Andrew Hunter</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload