Why should I use IDisposable instead of using in c#?

前端 未结 6 1792
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 07:59

Today, I wanted to perform an operation with a file so I came up with this code

    class Test1
    {
        Test1()
        {
            using (var fileSt         


        
6条回答
  •  清酒与你
    2021-01-03 08:23

    I think that the question is more like "Should I dispose the file immediately or with the Dispose method of the class that accesses to that file?"

    It depends: if you access the file only in the constructor in my opinion there is no reason to implement the IDisposable. Using is the right way

    Otherwise if you use the same file also in other methods, maybe it's a good practise open the file once and be sure to close it in your Dispose method (implementing the IDisposable)

提交回复
热议问题