When you are passing a class (any class, including Array) to a method without the "ref" keyword, you are still actually passing a reference to the actual object.
Consider the following code:
-
class Program
-
{
-
public class Data
-
{
-
public int a;
-
}
-
-
public static void Change(Data data)
-
{
-
data.a = 20;
-
}
-
-
static void Main(string[] args)
-
{
-
Data data = new Data();
-
data.a = 10;
-
-
Change(data);
-
Console.WriteLine(data.a); // a is now 20
-
}
-
}
-
You can see that "data" variable is pointing to the same object during its lifetime. The "Change()" method accesses that object and
really changes the "a" property,
although it is not passed with a "ref" keyword.
If we had passed "data" using a "ref" keyword, we would be actually passing a reference to our "data" variable, not to the actual object. In that case, we could make "data" point somewhere else inside the "Change()" method, and it would reflect in the main program also.
So, when passing a reference value (any class instance) to a method, remember:
- Without "ref" keyword - you are passing a reference to your object
- With "ref" keyword - you are passing a reference to the actual variable which points to your object