Search code examples
c#try-catchusing

c# "using" statement follow by try statement can the bracket be ombitted in that case?


  using System.Net;       // (See Chapter 16)
   ...
  string s = null;
  using (WebClient wc = new WebClient()) // why there is no brackets after this using statement
      try { s = wc.DownloadString ("http://www.albahari.com/nutshell/");  }
      catch (WebException ex)
      {
        if (ex.Status == WebExceptionStatus.Timeout)

          Console.WriteLine ("Timeout");
        else
          throw;     // Can't handle other sorts of WebException, so rethrow
      }

The above code is copy from Page 153 c# in a Nutshell, I don't understand why the { } are missing after the using statement, is that a typo in the book (unlikely) or just not needed? As the syntax is that using need to follow by a block of code inside {}.

I would expect this code to be:

  using System.Net;       // (See Chapter 16)
   ...
  string s = null;
  using (WebClient wc = new WebClient()) // why there is no brackets after this using statement
  {
      try { s = wc.DownloadString ("http://www.albahari.com/nutshell/");  }
      catch (WebException ex)
      {
        if (ex.Status == WebExceptionStatus.Timeout)

          Console.WriteLine ("Timeout");
        else
          throw;     // Can't handle other sorts of WebException, so rethrow
      }
  }

Solution

  • If you look at the grammar of the using statement in the C# Specification, you see that using statements are followed by (or rather, their body consists of) "embedded_statements".

    using_statement
        : 'using' '(' resource_acquisition ')' embedded_statement
        ;
    

    Embedded statements are defined as follows:

    embedded_statement
        : block
        | empty_statement
        | expression_statement
        | selection_statement
        | iteration_statement
        | jump_statement
        | try_statement
        | checked_statement
        | unchecked_statement
        | lock_statement
        | using_statement
        | yield_statement
        | embedded_statement_unsafe
        ;
    

    So yes, this is not a typo. After using (...), there can be any of the statements that are defined in embedded_statement. And anyway, to see whether this is a typo, you could have just simply tried to compile the example code.