Click here to Skip to main content
15,347,000 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As per my understanding, dispose() method is used to deallocate memory space for unmanaged resources.

Now when we create an object of streamreader class, we can call close method multiple time(i.e. we can open and close multiple file).
StreamReader sreader=new StreamReader("a.txt");
sreader=new StreamReader("b.txt");

Now in above code if I didn't call sreader.Dispose(), then does memory deallocation will occur using finalize() method(i.e. by garbage collector) or does it will going to create any memory leaks.

Please let me know if you have any idea.
Updated 14-Nov-11 18:36pm

1 solution

Generally, Finalize has nothing to do with Dispose. You never need to call Finalize as GC does it, but you need to call Dispose for all object implementing this interface. The call to Close calls Dispose(true), according to[^].

Calling this method is important to free unmanaged resources and especially important for StreamWriter (otherwise you can loose the results of writing), so the call should be done in finally part of try-finally block:

sreader=new StreamReader("b.txt");
try {
} finally {

Sujeet Pardeshi 15-Nov-11 3:02am
Thanks for the reply.

It means that calling close() method will going to deallocate memory for object as well. But then which method we should???? close() or dispose()
I would recommend using the pattern I've shown in the above code sample. Close does call Dispose(true).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900