Global and Local Variables in C#

CsharpProgrammingServer Side Programming

Local Variables

A local variable is used where the scope of the variable is within the method in which it is declared. They can be used only by statements that are inside that function or block of code.

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      int a;
      a = 100;
      // local variable
      Console.WriteLine("Value:"+a);
   }
}

Output

Value:100

Global Variables

C# do not support global variables directly and the scope resolution operator used in C++ for global variables is related to namespaces. It is called global namespace alias.

If you have a type that share an identifier in different namespace, then to identify them use the scope resolution operator. For example, to reference System.Console class, use the global namespace alias with the scope resolution operator −

global::System.Console

Example

using myAlias = System.Collections;
namespace Program {
   class Demo {
      static void Main() {
         myAlias::Hashtable hTable = new myAlias::Hashtable();
         hTable.Add("A", "1");
         hTable.Add("B", "2");
         hTable.Add("C", "3");
         foreach (string str in h.Keys) {
            global::System.Console.WriteLine(str + " " + h[n]);
         }
      }
   }
}
raja
Published on 31-Aug-2018 11:49:57
Advertisements