Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
      }
  }
like image 840
Huibin Zhang Avatar asked Dec 13 '17 17:12

Huibin Zhang


2 Answers

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.

like image 103
adjan Avatar answered Nov 19 '22 04:11

adjan


If the {} are omitted the next statement is the statement under the using. In this case that would be the try statement.

It's similar to the if statement (or any other):

if(x == 0) return; // No {} the next statement is affected by the if

{} basically groups several statements together turning it into a single statement so basically the same rule applies.

like image 1
Titian Cernicova-Dragomir Avatar answered Nov 19 '22 06:11

Titian Cernicova-Dragomir