What are the differnt categories of variables available in C#?

 Posted by Nagasundar_Tn on 11/29/2012 | Category: C# Interview questions | Views: 1475 | Points: 40
Answer:

C# has seven types of variables.

They are

local variables           -- Variables declared inside method or function.

instance variables -- Declares at class level scope
static variables -- which contains Static keyword before variable data type.
array elements, -- Array variable. Contains sequence of memory locations.
value parameters, -- Value type variable passed in parameters
reference parameters -- Reference type variable passed in parameters
output parameters -- Out type variable passed in parameters


There is no global variable in C#. Because it breaches the encapsulation concept.

class Program

{
int VarClassScope = 42;
static int VarStatic = 5;

public void FncVariables(int VarValueParam, ref int VarRefParam, out int VarOutParam)
{
VarOutParam = 100;
VarRefParam = 50;
VarValueParam = 25;
}

static void Main(string[] args)
{
Program pObj = new Program();
int VarFunctionScope = 23;
int[] VarArrVariable = new int[1];
VarArrVariable[0] = 22;
Console.WriteLine("Class variable = " + pObj.VarClassScope);
Console.WriteLine("Function variable = " + VarFunctionScope);
Console.WriteLine("Static variable = " + VarStatic);
Console.WriteLine("Array Element variable = " + VarArrVariable[0]);

int VarOutParam = 10; //No use of initializing here for OUT
int VarRefParam = 10;
int VarValueParam = 10;
pObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);

Console.WriteLine("Value Param Variable = " + VarValueParam);
Console.WriteLine("Reference Param Variable = " + VarRefParam);
Console.WriteLine("Out Param Variable = "+ VarOutParam);

Console.Read();
}

}


In the above code I am initializing all kinds of variables. Note the line

 pObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);

I am calling the "FncVariable"s function which accepts value, referene and out type variables. Before calling the function all variables have value 10.
But after calling the "FncVariable"s function, value type variable remains unchanged but ref and out type variables changed.

The output is

Class variable = 42

Function variable = 23
Static variable = 5
Array Element variable = 22
Value Param Variable = 10
Reference Param Variable = 50
Out Param Variable = 100


Source: http://msdn.microsoft.com/en-u | Asked In: Telephone interview | Alert Moderator 

Comments or Responses

Login to post response