I was chatting to someone on IM tonight (name withheld at the correspondents’ request) about a couple of basic coding matters…the assertion he made was that if you pass a reference type to a method it is exactly equivalent to passing a reference type with the ‘ref’ modifier…well, here’s a piece of code to test the theory. What would you expect the result to be and why (simple little console app in case anyone wants to try it out)…?

using System;

using System.Collections;

 

namespace ConsoleApplication3

{

    /// <summary>

    /// Summary description for Class1.

    /// </summary>

    class Class1

    {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main(string[] args)

        {

            ArrayList al = new ArrayList(2);

            ArrayList al2 = new ArrayList(2);

            SetNull(al);

            SetNull(ref al2);

            Console.WriteLine(al ==null);

            Console.WriteLine(al2==null);

            Console.ReadLine();

 

        }

 

        private static void SetNull(ref ArrayList al)

        {

            al = null;

        }

 

        private static void SetNull(ArrayList al)

        {

            al=null;

        }

    }

}

UPDATE: As AndyB pointed out in the comments, this article has a great explanation of the differences between passing by ref and passing by val...oh, and of course, the bible also includes a great discussion of these issues...