The Out keyword causes parameters to be passed by reference. This is similar to the REF keyword, except that the ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the Out keyword. For example:
Class Outexample {static void Method (out int i) {i =;} static void Main () {int value; Method (out value); Value is now 44}}
Although a variable passed as an out parameter does not need to be initialized before it is passed, the method needs to be called to assign a value before the method returns.
The ref and out keywords are handled differently at run time, but are handled the same way at compile time. Therefore, if one method takes a ref parameter and the other method takes an out parameter, the two methods cannot be overloaded. For example, from a compilation point of view, the two methods in the following code are identical, so the following code will not be compiled:
Class Cs0663_example {//Compiler Error CS0663: "cannot define overloaded//methods that differ only on ref and out" public void SampleMethod (out int i) {} public void SampleMethod (ref int i) {}}
However, if a method takes a ref or out parameter and the other method does not take these two types of arguments, it can be overloaded as follows:
Class Refoutoverloadexample {public void SampleMethod (int. i) {} public void SampleMethod (out int i) {}} remarks
property is not a variable and therefore cannot be passed as an out parameter.
For information about passing arrays, see passing arrays with ref and out.
Example
Declaring an out method is useful when you want a method to return more than one value. A method that uses an out parameter can still use a variable as a return type (see return), but it can also return one or more objects to the calling method as an out parameter. This example uses out to return three variables in a method call. Note that the value assigned to the third parameter is Null. This allows the method to return a value selectively.
Class outreturnexample{static void Method (out int i, out string s1, out string s2) {i = 44; S1 = "I ' ve been returned"; s2 = null; } static void Main () {int value; String str1, str2; Method (out value, out str1, out str2); Value is now A//STR1 is now "I ve been returned"//STR2 is (still) null; }}
C # returns multiple parameters ref and out