InterviewSolution
| 1. |
Scope of Variables in C# |
|
Answer» The scope of variables specifies the program parts where the variable is accessible. There are mainly three categories for the scope of variables. These are given as follows: Class Level Scope The variables with class level scope are accessible ANYWHERE in the class. These variables are those that were declared INSIDE the class but outside any method. A program that demonstrates the variables with class level scope is given as follows: using System; class A { int a = 10; public void printa() { Console.WriteLine("a = " + a); } } class Demo { public static void Main() { A obj = new A(); obj.printa(); } }The output of the above program is as follows: a=10In the above program, the scope of the variable a is class level scope. Method Level Scope The variables with method level scope are accessible in the method only and not outside it. These variables are those that were declared inside the method. A program that demonstrates the variables with method level scope is given as follows: using System; class Demo { public void printb() { int b = 20; Console.WriteLine("b = " + b); } public static void Main() { Demo obj = new Demo(); obj.printb(); } }The output of the above program is as follows: b=20In the above program, the scope of the variable b is method level scope. Block Level Scope The variables with block level scope are accessible in the block only and not outside it. These variables are normally declared in loops such as for loop, while loop etc. A program that demonstrates the variables with block level scope is given as follows: using System; class Demo { public static void Main() { for (int i = 1; i <= 5; i++) { Console.Write(i + " "); } } }The output of the above program is as follows: 1 2 3 4 5In the above program, the scope of the variable i is block level scope as it is only accessible inside the for loop. |
|