A function with a parameter with the out keyword gives the same result as with ref .

Such code:

 private void func(out string value) { value = "Hello World!"; } 

Gives the same effect as

 private void func(ref string value) { value = "Hello World!"; } 

What is the difference between out and ref ?

    1 answer 1

    The difference is that out is the output parameter, and ref is the input and output.

    For a ref parameter, you must pass it initialized, and you can use its original value. And for the out parameter, you are not required to initialize it before calling the function, you cannot use its value in the function before assignment, and you must initialize it in the function.

    (Thus, the ref parameter is a bit like an initialized local variable, and the out parameter is uninitialized .)

    Illustration:

     private void func1(out string value) { Console.WriteLine(value); // нельзя, value не инициализировано if (false) return; // нельзя, забыли установить значение value value = "Hello World!"; } string s1; func1(out s1); 
     private void func2(ref string value) { Console.WriteLine(value); // можно if (false) return; // не проблема, у value остаётся старое значение value = "Hello World!"; } string s2; func2(ref s2); // нельзя, функция имеет право использовать значение, // значит, оно должно быть инициализировано сначала 

    Thus, the out parameter is an additional return value of the function. And the ref parameter is simply a parameter whose changes are visible outside the function.


    At the CLR level, the same mechanism is used for the out and ref parameters, but this is a minor technical detail. The difference in semantics.