Hi Script,
MSDN document "using Statement(C# Reference)" says:
The using statement provides a convenient syntax that ensures the correct use of IDisposable objects.
File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.
As a rule, when you use an IDisposable object, you should declare and instantiate it in ausing statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within theusing block, the object is read-only and cannot be modified or reassigned.
You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves theusing block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside theusing block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in theusing statement and limit its scope to the using block.
So please ensure to instantiate the data context object within the using statement.
In addition, "dispose an object" only means releasing the managed and unmanaged resources used by the object, which doesn't mean destructing the object. It's GC that determines when to destruct the object.
Hope this helps.
Sincerely,
Linda Liu
MSDN Subscriber Support in Forum
If you have any feedback on our support, please contact
msdnmg@microsoft.com
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.