Language Basics C# Book

Parameter modifier Passed by
no modifier Value
ref Reference
out Reference
The parameters with out modifier the parameters must be assigned in the method
The parameters with ref modifier or no modifier must be assigned before passing into the method.
using System;
class Program
{
static void change(int i)
{
i = i + 1;
Console.WriteLine("in change method:" + i);
}
static void Main(string[] args)
{
int i = 2;
change(i);
Console.WriteLine("in main method:" + i);
}
}
The output:
in change method:3
in main method:2
From the output we can see that changing the value in change method has no effect on the variable i in main method.
For reference type parameters the value of the reference is copied not the object itself.
The following code defines a class Rectangle. Class is a reference type.
The change method accepts the Rectangle type as its parameter.
In the change method new value is assigned to the parameter.
using System;
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void change(Rectangle r)
{
r.Width = 10;
}
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
change(r);
Console.WriteLine(r.Width);
}
}
The output:
5
10
We can see that the main method gets the changed value from change method. The change method changes the value from the reference.
To see the effect of a copied reference we can change the code above as follows.
using System;
class Rectangle
{
public int Width = 5;
public int Height = 5;
}
class Program
{
static void change(Rectangle r)
{
r = null;
}
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
change(r);
Console.WriteLine(r.Width);
}
}
The output:
5
5
Even if we set the reference in change method to null, the r in the main method still points the rectangle object.