Trying to understand the 'using' statement better

后端 未结 8 1241
小鲜肉
小鲜肉 2021-01-18 17:26

I have read a couple of articles about the using statement to try and understand when it should be used. It sound like most people reckon it should be used as much as possib

相关标签:
8条回答
  • 2021-01-18 17:59

    Using statement is syntax sugar of C#.

    So the following code:

    using(var someDisposableObject = new someDisposableObject())
    {
        // Do Something
    }
    

    actualy looks like:

    var someDisposableObject = new someDisposableObject();
    try
    {
      // Do Something
    }
    finally
    {
       if (someDisposableObject != null)
       {
           ((IDisposable) someDisposableObject).Dispose();
       }
    }
    

    Look at this article: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

    0 讨论(0)
  • 2021-01-18 18:02

    One time I can think of where you wouldn't want to use 'using' on connections would be on ClassFactories for connected objects such as DataReaders, e.g. consider the case

    private IDataReader CreateReader(string queryString,
        string connectionString)
    {
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(queryString, connection);
        connection.Open();
        return command.ExecuteReader(CommandBehavior.CloseConnection);
        // Don't close connection
    }
    

    (Modified from MSDN - The example on MSDN is just plain stupid)

    Another reason is on WCF ServiceReference 'clients' - if the channel becomes faulted, 'using' then hides the actual exception. But this is just a buggy implementation IMHO.

    0 讨论(0)
提交回复
热议问题