站内搜索: 请输入搜索关键词
当前页面: 图书首页 > NET For Java Developers Migrating To C#

NET For Java Developers Migrating To C#

[ directory ] Previous Section Next Section

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 variable name, it is a bad practice. Lack of code readability may not be an issue for a snippet, but can be nerve-wracking in a large project. C# has taken steps to discourage this by disallowing the practice of using the same variable name. That does not mean you cannot use something like the following:

using System;
public class Person {
  string name;
  int age;
  public Person (string name, int age) {
    this.name = name;
    this.age = age;
  }
}

Here, the name and age variables are qualified using the this keyword, which the compiler recognizes.

Method variables or class variables must be initialized in C# before they can be accessed. Therefore, the following class doesn't compile:

using System;
public class Test {
  public static void Main(string[] args) {
    int n;
    Console.WriteLine("Value of n is ", n);
  }
}

That's because the local variable n is not initialized. Class variables assume a default value. In the case of int n in the following code, the default value is 0:

using System;
public class Test {
  int n;
  public static void Main(string[] args) {
    Test t = new Test();
    Console.WriteLine("Value of n is ", t.n);
  }
}

You don't have to initialize arrays and structs before accessing them.

    [ directory ] Previous Section Next Section