If I return a value inside a using block in a method, does the using dispose of the object before the return?

前端 未结 2 448
走了就别回头了
走了就别回头了 2020-12-11 08:03

I\'m going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.

2条回答
  •  一个人的身影
    2020-12-11 08:42

    Yes it will still call dispose.

    Run this very simple console application top verify:

       class Program
        {
            static void Main(string[] args)
            {
                TestMethod();
                Console.ReadLine();
            }
    
            static string TestMethod()
            {
                using (new Me())
                {
                    return "Yes";
                }
            }
        }
    
        class Me : IDisposable
        {
            #region IDisposable Members
    
            public void Dispose()
            {
                Console.WriteLine("Disposed");
            }
    
            #endregion
        }
    

提交回复
热议问题