Alex Rivera | Logout

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

Asked 2009-11-05T20:33:00.217
9

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.

Edit
Report

1 Answer

1

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.

answered 2009-11-05T20:39:25.087

Your Answer