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?

Community
  • 1
  • 1
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199

1 Answers1

3

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
  • 14,234
  • 2
  • 31
  • 52