What is the difference between Dispose and Close? [duplicate]
Possible Duplicate:
Close and Dispose - which to call?
Hi,
After reading some web pages, I still don't understand the difference between Dispose and Close methods in C#.
Let's take a sample:
using (SqlConnection sqlConnection = new SqlConnection())
{
// Execute an insert statement (no breaks, exceptions, returns, etc.)
}
and a second one:
SqlConnection sqlConnection = new SqlConnection();
// Execute an insert statement (no breaks, exceptions, returns, etc.)
sqlConnection.Close();
Are those two pieces of code similar? Are both available only for convenience (since there a开发者_StackOverflow社区re situations where using
is not a solution? Or there is a difference in the behavior?
So why some classes provide Close
method and when should I put a Close
method in IDisposable
classes I create?
Your two code snippets are equivalent.
.NET classes that implement IDisposable
and expose Close
, do it juts for the added convenience of having a Close
method that has a slightly friendlier name. Typically one calls the other.
If you implement your own disposable class, you won't need to add a Close
method, unless you like to have one.
精彩评论