When do we need to call Dispose() in dot net c#?

回眸只為那壹抹淺笑 提交于 2019-11-28 10:12:00

Rule of thumb: if a class implements IDisposable you should always call the Dispose method as soon as you have finished using this resource. Even better wrap it in a using statement to ensure that the Dispose method will be called even if an exception is thrown:

using (var reader = conn.ExecuteReader())
{
    ...
}

Object which are Disposable can be best used (if possible) in a using block. At the end of the using block, the object is automatically disposed.

Because of memory management it is always advised do dispose your objects if you don't need them anymore.

Here's some stuff to read from the MSDN.

There is a simple guideline: if you have finished with an object whose type implements IDisposable then call Dispose() on it; you should use a using block to do this.

It is recommended to use the using pattern when dealing with anything that implements IDisposable

using ()
{
    // use it here
}

This will look after the try..catch..finally construct and calling Dispose.

EDIT I had previously said that I thought Close and Dispose did the same thing for readers (stream, file, sqldatareader etc.) but it appears this is not true looking at the documentation on SQLDataReader so my assumption was wrong.

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