The object references you create in your application follow the normal scoping rules that you would expect. For example, if you create an object reference inside a method, then it will only exist until the method returns control to its caller. If you create a reference inside a For
loop, then the reference is in scope only for that loop. However, that does not mean the object the reference was pointing to goes away immediately. In managed environments such as .NET, a garbage collector handles destroying the objects in memory only after an object no longer has any references pointing to it. Even then, the GC will schedule the appropriate time to handle this in the background and does not necessarily perform the garbage collection as soon as the number of references to an object reaches 0.
See this article for an introduction to the concepts of garbage collection in .NET.
There are exceptions to this rule when your application is referencing objects created using unmanaged resources, or resources that are not directly controlled by the CLR. A typical example of this might be a database connection or network socket. In these cases you may need to actually call Dispose
on an object in order to ensure that its resources are freed.
See this question for a nice explanation of why and when to use IDisposable
.