Yes, we don't have to worry about memory management. However, flush of the stream has nothing to do with memory management. We need to take care about the flush and closing of the stream. Pay attention: many classes implement
System.IDisposable
. You need to make sure
IDisposable.Dispose
for such classes is always called when their work is done. One good way of doing so is using "using" statement (not to be mixed up with using clause), see
http://msdn.microsoft.com/en-us/library/yh598w02%28v=VS.100%29.aspx[
^].
In some classes a failure to dispose can cause additional trouble:
a leak of unmanaged memory.
Finally, if you think that GC saves you from
leak of managed memory, think again. Yes, it totally guards you against accidental leaks, when you forget to delete some object (there is no delete),
but you can easily cause the leak by design mistakes. Remember, an object is scheduled for execution when the running code looses all references to it. Even if object A references object B, B references C and C references A this situation is resolved and they all are destroyed if there are no more references to either of them.
Imagine you create and delete some objects (for example, Forms) and expect the memory allocation to come into the same point when the number of these objects comes to zero. It will work. Now imagine you have a global object such as Dictionary used to hold all those objects for the purpose of quick finding them, say, by name. If you forget to delete references from an instance of the Dictionary, references will be collected there forever effectively preventing destruction — you created a memory leak.
It can happen whenever you have some
singleton in the Application Domain. One other technique to solve this problem is
System.WeakReference
, see
http://msdn.microsoft.com/en-us/library/system.weakreference.aspx[
^].
[EDIT]
Please see also my recent answer on a related topic:
deferring varirable inside the loop can cuase memory leak?[
^].
—SA