.NET - Replacing nested using statements with single using statement

后端 未结 5 796
说谎
说谎 2021-01-12 19:08

If you came across some C# code like this with nested using statements/resources:

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 19:50

    I posted this elsewhere, but separating your declarations by comma seems to treat each statement separated this way as a new declaration and disposes of them.

    using (IType1 a = new Type1(), b = new Type1()){}

    This however means your objects must be of the same type. You could call them like

    using (IDisposable a = new Type1(), b = new Type2()){}

    But then of course, you only have access to IDisposable methods, without casting the object, which is kinda dumb. So instead, I believe you can use

    using (var a = new Type1(), b = new Type2()){}

    This appears to give you the correctly typed object references allowing you access to the proper method of the allocated type, and disposes of both objects created. If anyone knows why I'm not right, please let me know because this appears to work for me? (I know this question is really old n stuff, but it's all I could find while searching for this answer myself)

提交回复
热议问题