Search code examples
c#pass-by-referencerefout

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


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.

PASS BY REFERENCE

Passing by reference means a reference to the original is passed. changes to the reference affect the original.

REF Keyword

REF tells the compiler that the object is initialized before entering the function. REF means the value is already set, the method can therefore read it and modify it. REF is two ways, both in and out.

OUT Keyword

OUT tells the compiler that the object will be intialized inside the function. OUT means the value is not already set, and therefore must be set before calling return. OUT is only one way, which is out.

Question

So in what scenarios would you combine the use of the ref and out keywords, with passing by reference or passing by value? Examples would help tremendously.

Help greatly appreciated.


Solution

  • 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
    }