Though both ref and out parameters are used to pass arguments through a method, they aren’t used in exactly the same way.
Ref keywords are used to pass an argument as a reference, meaning that when the value of that parameter changes after being passed through the method, the new value is reflected in the calling method. An argument passed using the ref keyword must be defined in the calling method before getting passed to the called method.
Out keywords similar to ref keywords in that they are used to pass an argument, but they differ in that arguments passed using out keywords can be passed without any value to be assigned to it. An argument passed using the out keyword must be defined in the called method before being returning to the calling method.
[code language=”csharp”] public class Keywords{
public static void Main() //calling method
{
int val1 = 0; //must be defined
int val2; //optional
Keywords1(ref val1);
Console.WriteLine(val1); // val1=7
Keywords2(out val2);
Console.WriteLine(val2); // val2=9
}
static void Keywords1(ref int value) //called method
{
value = 7;
}
static void Keywords2(out int value) //called method
{
value = 9; //must be defined
}
}
/* Output
7
9
*/
[/code]
In the example above, you can see the differences between ref and out keywords in action. In the first few lines, we assign a value to val1 but not val2, because val1 will be passed through an argument using the ref keyword, meaning that an initial value must be assigned to it. The out keyword value (val2) isn’t defined until the called method towards the end of the code, because it must be defined in the called method before being passed to the calling method. The calling methods above are asking for the value of the parameters to be written to the console, so the output would be 7 and 9 for val1 (ref) and val2 (out), respectively.