The ref keyword causes arguments to be passed by reference. The effect is that any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword
An argument passed to a ref parameter must first be initialized. This differs from out, whose argument need not be explicitly initialized before being passed
Although ref and out are treated differently at run-time, they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.
These two methods, for example, are identical in terms of compilation, so this code will not compile:
class CS0663_Example
{
// compiler error CS0663: "cannot define overloaded
// methods that differ only on ref and out"
public void SampleMethod(ref int i) { }
public void SampleMethod(out int i) { }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:
class RefOutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}