4.7. Variable Scoping

In C#, local variables can be given only those names that allow them to be uniquely identified within a scope. The following code illustrates variable scoping:

using System;
public class Test {
  public static void Main(string[] args) {
    int i = 4;
    for (int j = 0; j < 10; ++j) {
      int i = 6 *j;
    }
  }
}

If you cut and paste this snippet, the compiler will complain, stating the following:

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'parent or current' scope to denote something else.

This restriction is new to Java programmers because this code would compile and run fine in Java.

Although it is easy to create nested scopes having the same ...

Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.