0

I have code that contained two using statements. The Inner using statement is reading a response stream and the outer is opening a file to write the response too.

The following code works fine (sfd is a SaveFileDialog):

using (Stream fs = sfd.OpenFile())
using (var responseStream = response.GetResponseStream())
{
    // Work
}

The following does not work

using (Stream fs = sfd.OpenFile())
{
    using (var responseStream = response.GetResponseStream())
    {
        // Work
    }
}

The only difference is that I inputted the curly braces to make the code more readable, but that breaks the code. Any ideas as to why? It does not quite make sense yet.

halfer
  • 19,824
  • 17
  • 99
  • 186
Keenan Stewart
  • 594
  • 6
  • 9
  • 6
    is it throwing a `DoesNotWorkException`? – Sam I am says Reinstate Monica Sep 10 '19 at 17:50
  • 1
    This is a quirk in the design of C#. If using VS the auto-formatter should remove the outer curly brackets for you. I personally agree that nesting with brackets makes the code more intuitive and doing it in this way just makes it confusing. But you'll have to ask Microsoft why they prefer this over the common-sense syntax. – DetectivePikachu Sep 10 '19 at 17:52
  • 8
    There is no difference for the code you posted; it will work the same either way. Your actual code must therefore be different from what you posted... – Matthew Watson Sep 10 '19 at 18:01
  • Thanks @DetectivePikachu .. I was annoyed by this for a bit and finally just reverted my code. Glad others see this issue too. – Keenan Stewart Sep 10 '19 at 18:47

0 Answers0