Scope Clashes for Fields and Local Variables

Scope Clashes for Fields and Local Variables

 

 We can distinguish between two identifiers with the same name  and the same scope, and  in this case the compiler will allow

We to declare the second variable. The reason is that C# makes a fundamental distinction between variables that are declared at

the type level  and variables that are declared within methods

Consider the following code snippet:

 

using System;

namespace awa

{

class ScopeTest2

{

static int j = 20;

Console.WriteLine(j);

public static void Main()

{

int j = 30;

Console.WriteLine(j);

return;

}

}

}

 

This code will compile, even though you have two variables named j in scope within the Main() method:

the j that was defined at the class level,  and doesn ' t go out of scope until the class is destroyed

(when the Main() method terminates, and the program ends); and the j defined in Main() .

 In this case, the new variable named j that you declare in the Main() method hides the class - level variable with the

same name, so when you run this code, the number 30 will be displayed.  However, what if you want to refer to the class - level variable?

You can actually refer to fields of a class or struct from outside the object, using the syntax object.fieldname . In the previous example,

you are accessing a static field (you look at what this means in the next section) from a static method, so you

can ' t use an instance of the class; you just use the name of the class itself:

 

public static void Main()

{

int j = 30;

Console.WriteLine(j);

Console.WriteLine(ScopeTest2.j);

}

 

If you were accessing an instance field (a field that belongs to a specific instance of the class), you would

need to use the this keyword instead. This keyword performs the same role as this in C++ and Java,

and Me in Visual Basic.

 

Next Recommended Reading Variables and Data Types(sql server)