Should I be using SqlDataReader inside a “using” statement?

前端 未结 3 1626
醉酒成梦
醉酒成梦 2020-12-29 03:02

Which of the following two examples are correct? (Or which one is better and should I use)

In the MSDN I found this:

private static void ReadOrderDat         


        
3条回答
  •  囚心锁ツ
    2020-12-29 03:14

    The second option means your reader will be closed in the event of an exception after it has been created, so it is preferred.

    It is effectively transformed by the compiler to:

    SqlDataReader reader = command.ExecuteReader();
    try
    {
        ....
    }
    finally
    {
      if (reader != null)
          ((IDisposable)reader).Dispose();
    }
    

    See MSDN for more info.

提交回复
热议问题