SoFunction
Updated on 2025-03-06

In-depth analysis of the value passing method and reference passing method of calling parameters in c# method, as well as the difference between ref and out


#define Test

using System;

namespace
...{

 class ParemeterTest
 ...{
    static void TestInt(int[] ints,int i)
    ...{
        ints[0] = 100;
        i = 100;
    }

     static void TestInt(int[] ints, ref int i)
     ...{
         ints[0] = 200;
         i = 200;
     }

     static void TestInt2(int[] ints, out int i)
    ...{
        ints[0] = 300;
        i = 300;
    }

 
    public static void Main()
    ...{
        int i=0;
        int[] ints = ...{0,1,2,3,4};

        ("-----------TestInt------------------");

        ("i={0}",i);
        ("ints[0]={0}",ints[0]);
        ("------------------------------------");

//By default, all parameters of c# are referenced by value, so when the value type i is called above, only a copy is transmitted. The function only affects the value of the copy during the call process, and does not actually affect the value of the i value.
        TestInt(ints, i);

("i={0}",i);//The output value of i here is still 0
        ("ints[0]={0}",ints[0]);
        ("------------------------------------");

//If you want to change the value of i, you can use ref to let the parameter i be passed to the function through a reference
        TestInt(ints, ref i);

("i={0}",i);//The output value of i here is 200
        ("ints[0]={0}",ints[0]);
        ("------------------------------------");

//To change the value of i, you can also use the out keyword to make
        TestInt2(ints, out i);

("i={0}", i);//The output value of i here is 300
        ("ints[0]={0}", ints[0]);
        ("------------------------------------");

//Ref is very similar to out, but there are also differences. Ref must require parameter initialization, but out does not need to
#if Test//To test the following two lines, remove the comments on the first line of the code #define Test
            int j;       
SomeFunction(ints, ref j);//An error will be reported during compilation: Unassigned local variable "j" is used
        #endif

        int k;
        TestInt2(ints, out k);
        ("k={0}", k);
        ("------------------------------------");       

        ();
    }
 }

 
}