They are mainly used to get multiple return values from a method call. Personally, I tend not to use them. If I want to get some return values from a method, I will create a small class to store them.
ref and out are used when you want to return something from a method in this parameter. As far as I remember, they both actually come down to the same IL, but C # adds some additional things, so you have to be specific.
Here are some examples:
static void Main(string[] args) { string myString; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = "Hello"; }
The above will not compile because myString is never initialized. If myString is initialized to string.Empty, then the output of the program will be an empty string, because all MyMethod0 this assigns a new line to the local link to param1.
static void Main(string[] args) { string myString; MyMethod1(out myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod1(out string param1) { param1 = "Hello"; }
myString is not initialized in the Main method, but the program displays "Hello". This is because the link myString in the Main method is updated with MyMethod1. MyMethod1 does not expect param1 to already contain anything, so it can be left uninitialized. However, the method must assign something.
static void Main(string[] args) { string myString; MyMethod2(ref myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod2(ref string param1) { param1 = "Hello"; }
This, again, will not compile. This is because ref requires myString in the Main method to be initialized first with something. But, if the Main method is changed so that myString is initialized to string.Empty, then the code will compile, and the output will be Hello.
Thus, the difference cannot be used with an uninitialized object; ref must be passed to the initialized object. And if you pass an object without reference to it, it cannot be replaced.
Just to be clear: if the passed object is already a reference type, then the method can update the object, and the updates are reflected in the calling code, however, the reference to the object cannot be changed. Therefore, if I write the code as follows:
static void Main(string[] args) { string myString = "Hello"; MyMethod0(myString); Console.WriteLine(myString); Console.ReadLine(); } public static void MyMethod0(string param1) { param1 = "World"; }
Exiting the program will be Hello, not World, because the method only changed its local copy of the link, not the link that was passed.
Hope this makes sense. My general rule is simply not to use them. I feel this is a return to the days before the TOE. (But, this is just my opinion)