Calling Dispose() vs when an object goes out scope/method finishes

前端 未结 6 727
情深已故
情深已故 2020-12-30 05:58

I have a method, which has a try/catch/finaly block inside. Within the try block, I declare SqlDataReader as follows:

SqlDataReader         


        
6条回答
  •  旧时难觅i
    2020-12-30 06:30

    The Dispose pattern doesn't make any guarantees about which objects will call Dispose on which other objects; it may happen sometimes, but you shouldn't care. Instead, it's your responsibility to make sure Dispose() is called for all IDisposable objects. The best way to do that is with the using statement. For example:

    using (SqlDataReader aReader = aCommand.ExecuteReader())
    {
        // your code
    }
    

提交回复
热议问题