C# pass by reference
ref keyword indicates that the parameter is passed by reference. The parameter must be initiated before passing.
The parameter value may be changed inside the function, and the changed value will be returned outside the function.
public void f(ref int k)
{
k = k + 8;;
}
int i = 2;
f(ref i); //i = 10
out keyword is similiar to
ref keyword, indicates that the parameter will be passed as reference.
The difference is that
out keyword do not need the parameter to be initialized before passed.
public void f(out int k)
{
k = 77;
}
int i;
f(out i); //i=77 now
f(ref i); //compile error, i is not defined
Since the parameter may not be initialized, it need to be initialized in the function, otherwise a compile error will occur.
public void f(out int k)
{
k = k + 5; //compile error, k is not defined
}
int i = 9;
f(out i); //error
ref do not had such issue.
public void f(ref int k)
{
k = k + 5; //ok
}
int i = 9;
f(ref i); //i=14 now