开发者

What is the difference between Dispose and Close? [duplicate]

开发者 https://www.devze.com 2023-01-06 11:47 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Close and Dispose - which to call?
This question already has answers here: Closed 12 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消