C# ref and out parameters

I was coding along and suddenly had a duh moment of what’s the difference between ref and out.  I knew how they work and I’ve used them sparingly before but I didn’t really have a concrete idea of the difference.

So I looked it up
Out = An additional return value

string doot;
int rawr;

rawr = SomeFooMethod(out doot);

Note: This is not to be abused as stated in the MSDN article  “As a matter of good programming style if you find yourself writing a method with many out parameters then you should think about refactoring your code. One possible solution is to package all the return values into a single struct.” — Mental note applied!

Ref = Considered initially assigned by the callee

The MSDN has a much better example than I do….

class RefExample
{
      static object FindNext(object value, object[] data, ref int index)
      {
            // NOTE: index can be used here because it is a ref parameter
            while (index < data.Length)
            {
                  if (data[index].Equals(value))
                  {
                        return data[index];
                  }
                   index += 1;
            }
             return null;
      }

      static void Main()
      {
            object[] data = new object[] {1,2,3,4,2,3,4,5,3};

            int index = 0;
            // NOTE: must assign to index before passing it as a ref parameter
            while (FindNext(3, data, ref index) != null)
            {
                  // NOTE: that FindNext may have modified the value of index
                  System.Console.WriteLine("Found at index {0}", index);
                  index += 1;
            }

            System.Console.WriteLine("Done Find");
      }
}

So there you have it. The difference between ref and out

 - Jeremy

Author: Jeremy

See all posts by Jeremy (35)

Leave a Reply

*