Visual C# Guide
Parameters

Both procedures and functions can accept parameters. When we specify the parameters for a procedure or function, we must also specify the data types. There are two ways to pass parameters to procedures and functions,

  • Passing By Value
  • Passing By Reference

By Value

In the following program, the parameters a and b are passed by value. This means that the values of the variables are used by the procedure, but not the variables themselves. Within the procedure, a and b are local variables that have no effect on the global variables with the same name.

static int a, b;
static void Main(string[] args)
{
   a = 3;
   b = 5;
   Cube(a, b);
   Console.WriteLine("Value of a in Main: {0}", a);
   Console.WriteLine("Value of b in Main: {0}", b);
   WaitForInput();
}
static void Cube(int a, int b)
{
   a = a * a * a;
   b = b * b * b;
   Console.WriteLine("Value of a in procedure: {0}", a);
   Console.WriteLine("Value of b in procedure: {0}", b);
}
static void WaitForInput()
{
   Console.WriteLine("Press enter to quit");
   Console.ReadLine();
}

Most of the time, we will want to pass parameters by value. This makes it easier for us to keep track of where in our program the values of variables change.

By Reference

If the keyword ref is used in the procedure definition and the procedure call, a reference to the variable is passed to the procedure. Any changes to the value of the variable within the procedure affects the global variable that was passed to it. Instead of telling the procedure what the value of the variable is, the program passes a reference to the location in memory where the variable is stored and the variable itself is altered.

static int a, b;
static void Main(string[] args)
{
   a = 3;
   b = 5;
   Cube(ref a, ref b);
   Console.WriteLine("Value of a in Main: {0}", a);
   Console.WriteLine("Value of b in Main: {0}", b);
   WaitForInput();
}
static void Cube(ref int a, ref int b)
{
   a = a * a * a;
   b = b * b * b;
   Console.WriteLine("Value of a in procedure: {0}", a);
   Console.WriteLine("Value of b in procedure: {0}", b);
}
static void WaitForInput()
{
   Console.WriteLine("Press enter to quit");
   Console.ReadLine();
}

Study the output from these two programs carefully.