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

前端 未结 7 659
南笙
南笙 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:51

    You would never combine ref and out on 1 parameter. They both mean 'pass by reference'.

    You can of course combine ref parameters and out parameters in one method.

    The difference between ref and out lies mainly in intent. ref signals 2-way data transport, out means 1-way.

    But besides intent, the C# compiler tracks definite-assignment and that makes the most noticable difference. It also prevents the misuse (reading) of an out parameter.

    void SetOne(out int x) 
    {
      int y = x + 1; // error, 'x' not definitely assigned.
      x = 1;         // mandatory to assign something
    }
    
    void AddTwo(ref int x)
    {
        x = x + 2;  // OK, x  is known to be assigned
    }
    
    void Main()
    {
        int foo, bar;
    
        SetOne(out foo); // OK, foo does not have to be assigned
        AddTwo(ref foo); // OK, foo assigned by SetOne
        AddTwo(ref bar); // error, bar is unassigned
    }
    

提交回复
热议问题