Does connection close when command is disposed and the connection is defined directly on the command?

本秂侑毒 提交于 2019-12-01 16:18:21

No, SqlCommand never attempts to close/dispose of the connection.

No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use using blocks whenever you can.

It does not close the connection, you need to either close it yourself or put it in its own using statment.

Also here is a tip to make your using blocks a bit more readable:

using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand())
{
    cmd.Connection = conn;
}

@milot

But my recommendation is to use using blocks whenever you can.

Using Using Blocks is nice but useless when working with non IDisposable Objects and so this can be confusing if you use Using Blocks anywhere.

Be careful since your objects might not being Disposed if they don't implements IDisposable.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!