The same and difference between ref and out in C#

Lionsure 2020-09-02 Original by the website

The out and ref keywords are sometimes used in the process of writing a program; because they are somewhat similar, they often give people some illusions. To use them correctly, a clear understanding of their differences is essential.

 

The same and difference between ref and out in C#

1. out and ref have the same point: they are all passed by address, and the original value is changed after the method is executed.

 

2. Difference between ref and out in C#:

1) When using ref, the passed-in arguments must be initialized; when using out, there is no need to initialize.

2) ref can pass the value of argument into the method; while out must clear the argument(even if the argument has been assigned), when exiting the method, all arguments of out must be assigned.

 

Specific examples are as follows:

using System;
       class RefOutTest
       {
              static void refTest(ref int a, ref int b)
              {
                     a = 10;
                     b = a;
              }

       static void outTest(out int a, out int b)
              {
                     //Before leaving this method, you must assign values to a and b, otherwise an error will be reported.
                     a = 10;
                     b = 20;
              }

              static void Main()
              {
                     int a = 1, b = 2;
                     refTest(out a, out b);
                     Console.WriteLine("a = {0}, b = {1}", a, b);

              int x,y;
                     outTest(out x, out y);
                     Console.WriteLine("x = {0}, y = {1}", x, y);
              }
       }

Program execution output:

a = 10, b = 10

x = 10, y = 20