开发者

Scope variables in C#?

开发者 https://www.devze.com 2023-03-24 23:21 出处:网络
I am reading some C# text regarding scope of variables and got some confusion: Case 1: class A { void F() {

I am reading some C# text regarding scope of variables and got some confusion:

Case 1:

class A
{
   void F() {
      i = 1;
   }
   int i = 0;
}
开发者_StackOverflow中文版

Case 2

class A
{
    void F()
    {
         i = 1;  // Error, use precedes declaration
         int i = 0;
     }
}

in both case 1 and 2, the variable i is used before it is declared and initialized but why the Case 2 got error? (I have read an explanation that because i is a global variable in case 1, but still want to know if there is another explanation)


int i is a class variable in Case 1. When the class is defined, all the variables defined in the scope of the class, not each method, are also defined.

In Case 2, you define the variable as part of the method, and AFTER you use it.


on Case 1, variable i is declared as an instance variable, so it perfectly valid if you declare a function that uses it first and then the variable declaration because when you call the method, automatically the variable is already been initialized.

on Case 2, variable i is a local variable to the function so it is not valid to do it like that.


When you declare variables inside a class code block that makes it a member variable, which is available to at least any of the functions in the class. If you create another function, it can also reference "i" as well. Your variable is delcared when an object for the class is instantiated.

It doesn't work in the second class because it wasn't declared at all beforehand.

0

精彩评论

暂无评论...
验证码 换一张
取 消