Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a matter of style. My considerations:</p> <ol> <li><p>If the code block is small, in the end it won't matter where you place the declaration. However, it's preferable to have declarations <em>nearer</em> use, mainly in large code blocks. First, this way you can make sure that the variable wasn't modified until that point in the block, and second, because you can check the type and initialization of the variable faster.</p></li> <li><p>Besides, its faster to <em>code</em> by declaring variables near where you use them -- you don't have to scroll back to the beginning of the scope just to declared a forgotten variable and then move back.</p></li> <li><p>This isn't faster or slower. Variables, no matter where declared in the scope, will have their allocation and initialization centered at the beginning of the scope. This can be checked by generating IL for the language. </p></li> </ol> <p>For example, the code:</p> <pre><code>static void Main(string[] args) { var a = 3; if (a &gt; 1) { int b = 2; a += b; } var c = 10; Console.WriteLine(a + c); } </code></pre> <p>Generates the following IL:</p> <pre><code>.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 24 (0x18) .maxstack 2 .locals init ([0] int32 a, // Declare a [1] int32 b, // Declare b [2] int32 c) // Declare c IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: ble.s IL_000c IL_0006: ldc.i4.2 IL_0007: stloc.1 IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: add IL_000b: stloc.0 IL_000c: ldc.i4.s 10 IL_000e: stloc.2 IL_000f: ldloc.0 IL_0010: ldloc.2 IL_0011: add IL_0012: call void [mscorlib]System.Console::WriteLine(int32) IL_0017: ret } // end of method Program::Main </code></pre> <p>One important thing to notice is that variables in internal scopes, such as the variable b, which was at the if scope, is declared at method scope by the compiler.</p> <p>Hope it helps.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload