Interesting little CLR question...

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...

Print | posted @ Friday, March 11, 2005 12:40 AM

Comments on this entry:

Gravatar # re: Interesting little CLR question...
by AndyB at 3/11/2005 10:14 AM

Yeah it's quite important to understand passing params, this is a classic example. Great article here explains all http://www.yoda.arachsys.com/csharp/parameters.html
Gravatar # re: Interesting little CLR question...
by Scott Galloway at 3/11/2005 10:39 AM

Yeah, reason I asked the question was that I became aware during the discussion that there's a common misconception that 'ref' modifiers have no real purpose when passing reference types as parameters. I do feel it's important to specify the ref modifier if you expect of modify the value of a parameter, partly because of the issue I specified in that code (changing the target of the reference) and partly to retain consistency when dealing with value types - whicn of course do not behave similarly when passed by val and passed by ref...

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 1 and 6 and type the answer here: