Scope Rules in C#

 

In C#, the scope  means declaration space of an identifier for a variable, reference or method is the portion of the program in which the identifier can be accessed. A local variable or reference declared in a block can be used only in that block or in blocks nested within that block.

 

The scope of variables or methods is depends on the access modifiers. In C# we have access modifiers Public, Private, Protected, Internal and Protected Internal. If you not mention any access modifier or access specifier all variables or methods scope is restricted to private by default.

 

 

The possible scopes for an identifier are class scope and block scope. Members of a class have class scope and are visible in what is known as the declaration space of a class. Class scope begins at the opening left brace ({) of the class definition and terminates at the closing right brace (}). Class scope enables methods of a class to access all members defined in that class.

 

In C#, Public variables or Public methods are not restricted to any scope whereas private variables scope is restricted to within the method where those defined and private methods can be accessible to within the class.

 

In a sense, all instance variables and methods of a class are global to the methods of the class in which they are defined (i.e., the methods can modify the instance variables directly and invoke other methods of the class). Identifiers declared inside a block have block scope (local-variable declaration space). Block scope begins at the identifier’s declaration and ends at the block’s terminating right brace (}). Local variables of a method have block scope, as do method parameters, which are local variables of the method. Any block may contain variable declarations.

 

 

Protected variables or Protected methods scope is restricted to within the class and within the derived class. Internal variables or Internal methods accessible within the class and within the assembly. Protected Internal variables or Protected Internal methods scope is restricted to within the class, within the derived class and within the assembly.

 

When blocks are nested in a method’s body, and an identifier declared in an outer block has the same name as an identifier declared in an inner block, an error is generated. On the other hand, if a local variable in a method has the same name as an instance variable, the value in the calling method (main program) is “hidden” until the method terminates execution. The reader should note that block scope also applies to methods and for structures. With for structures, any variable declared in the initialization portion of the for header will be in scope only within that for structure.