views:

80

answers:

1

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 are 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?

+1  A: 

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.

Mau
This is almost correct. `Dispose` and `Close` are the same *except* for database connection classes.
Stephen Cleary