المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : using statement Vs Dispose/Finalize pattern



C# Programming
07-31-2009, 11:30 AM
What difference I see between using statement and Dispose/Finalize pattern is

- “Dispose/finalize” have upper hand if any object which implements this pattern and supporting different interfaces for different operations which performed on underneath unmanaged object, can take care of releasing that object even if user forgets to call dispose on that object
- However with “Using” statement, the scope of the using statement will be restricted to a single method, i.e. we will have to open the unmanaged object which will closed automatically by using’s finally block in the same method (which is, in most of the cases will not be feasible and efficient as we don’t do all the operation at a time on the unmanaged objects)

For Example:
1.Dispose/Finalize:
Suppose, we are using MS word COM to write doc files, we dedicate one class to do all the activities related to doc file and provide different interfaces to write to doc file like WriteTest() , InsertTable(), InsertImage(), …and so on . In this situation user will keep calling these interfaces according to their needs, and might forgets to close the word doc object. In this case, we can very well implement Dispose/Finalize pattern where finalize method will be act as back up plan to release unmanaged word doc object.
This approach will be efficient as long as we are using the same unmanaged object.

2.Using statement
Suppose, we are writing to a text file and we have interface to do this operation which takes text data and file name as parameter. In this case we can use “Using” statement to open the file and write data to it (again supposing that we will not any further operation on this file). What Using statement we do is it add try and finally block to this text file call. Which I guess efficient solution.

Hey guys, anybody know other differences other than what I mentioned here

Or you can correct me, If I am wrong in my above made conclusions!!!!

http://www.barakasoft.com/script/Forums/Images/smiley_smile.gif