Using REF & OUT keywords with Passing by Reference & Passing by Value in C#

前端 未结 7 660
南笙
南笙 2021-01-12 06:32

Here is what I understand so far:

PASS BY VALUE

Passing by value means a copy of an argument is passed. Changes to that copy do not change the original.

7条回答
  •  半阙折子戏
    2021-01-12 06:50

    Edit: I have corrected this answer to reflect that the 'out' keyword in C# does not do what you might expect it to (eg a true OUT parameter in the computer science sense of the term). I originally stated that 'out' was pass by value OUT but was proven wrong.

    You can't use 'out' and 'ref' together. There are three calling conventions in C# (NET Framework):

    • No keyword = Pass by value (IN)
    • 'out' Keyword = Pass by reference (REF) with no definite assignment requirement before call
    • 'ref' Keyword = Pass by reference (REF) with a definite assignment requirement before call

    C# has no true OUT or IN-OUT parameter ability.

    To see that 'out' parameters in C# are not true OUT parameters, you can use the following code:

      public class Test
      {
        Action _showValue;
    
        public void Run()
        {
          string local = "Initial";
          _showValue = () => { Console.WriteLine(local.ToString()); };
    
          Console.WriteLine("Passing by value");
          inMethod(local);
    
          Console.WriteLine("Passing by reference with 'out' keyword");
          outMethod(out local);
    
          Console.WriteLine("Passing by reference with 'ref' keyword");
          refMethod(ref local);
    
        }
    
        void inMethod(string arg)
        {
          _showValue();
          arg = "IN";
          _showValue();
        }
    
        void outMethod(out string arg)
        {
          _showValue();
          arg = "OUT";
          _showValue();
        }
    
        void refMethod(ref string arg)
        {
          _showValue();
          arg = "REF";
          _showValue();
        }
      }
    

    The output is:

    Passing by value
    Initial
    Initial
    Passing by reference with 'out' keyword
    Initial
    OUT
    Passing by reference with 'ref' keyword
    OUT
    REF
    

    As you can see, both 'out' and 'ref' actually pass by REF. The only difference is in how the compiler treats them for definite assignment purposes.

提交回复
热议问题