In depth analysis of how the call parameters in the c method are passed by value and by reference and the differences between ref and out

  • 2020-05-17 06:13:34
  • OfStack


#define Test
using System;
namespace Wrox.ProCSharp.ParameterTestSample
...{
 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};
        Console.WriteLine("-----------TestInt------------------");
        Console.WriteLine("i={0}",i);
        Console.WriteLine("ints[0]={0}",ints[0]);
        Console.WriteLine("------------------------------------");
        // By default, c# All parameters are referenced by values, so value types i When the function above is called, all that is passed is 1 The function only affects the value of the copy during the call, right i The value doesn't really matter 
        TestInt(ints, i);
        Console.WriteLine("i={0}",i);// The output here i Value is still 0
        Console.WriteLine("ints[0]={0}",ints[0]);
        Console.WriteLine("------------------------------------");
        // If you want to change i The value of ref Let the parameters i Passed to the function by reference 
        TestInt(ints, ref i);
        Console.WriteLine("i={0}",i);// The output here i A value of 200
        Console.WriteLine("ints[0]={0}",ints[0]);
        Console.WriteLine("------------------------------------");
        // To change the i The value can also be passed out Key words to 
        TestInt2(ints, out i);
        Console.WriteLine("i={0}", i);// The output here i A value of 300
        Console.WriteLine("ints[0]={0}", ints[0]);
        Console.WriteLine("------------------------------------");
        //ref with out Similar, but different, ref Parameter initialization must be required, out You don't need to 
        #if Test// We're going to test the following 2 Line, put the code first 1 line #define Test Just uncomment it 
            int j;        
            SomeFunction(ints, ref j);// An error is reported at compile time :  Using an unassigned local variable." j " 
        #endif
        int k;
        TestInt2(ints, out k);
        Console.WriteLine("k={0}", k);
        Console.WriteLine("------------------------------------");        
        Console.ReadLine();
    }
 }

 
}

Operation results;
-----------TestInt------------------
i=0
ints[0]=0
------------------------------------
i=0
ints[0]=100
------------------------------------
i=200
ints[0]=200
------------------------------------
i=300
ints[0]=300
------------------------------------
k=300
------------------------------------


Related articles: