The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Jul 2008»»
SMTWTFS
  
1
2
3
4
5
6789101112
13141516171819
20212223242526
2728293031

My RSS Feeds








Mailing List

Most Popular Tags

                                       

The difference between array and ref array

posted Friday, 3 August 2007
Sometimes you'll want to pass an object (like an array) into a method, and have that method update the object. For an array, the common ways to do this are using the ref keyword, or modifying a member of an array. It's easy to confuse these two approaches because if you're just updating a member, they appear to have the same affect. However they're actually fundamentally different - passing in an array by ref lets you modify the array reference itself, such as changing it to a new array with a new length. The code snippet below illustrates this:

 

 

    #region Normal Array

    [TestMethod]
    public void TestMethod1()
    {
      //Normal array changes individual member
      string[] astr = new string[]{"aaa"};
      ModifyArray1(astr);
      Assert.AreEqual("bbb", astr[0]);
    }

    [TestMethod]
    public void TestMethod2()
    {
      //Non-ref array doesn't change array itself
      string[] astr = new string[] { "aaa" };
      ModifyArray2(astr);
      Assert.AreEqual(1, astr.Length);
      Assert.AreEqual("aaa", astr[0]);
    }

    public static void ModifyArray1(string[] astr)
    {
      astr[0] = "bbb";
    }

    public static void ModifyArray2(string[] astr)
    {
      astr = new string[] { "ccc", "ccc" };
    }

    #endregion

    #region Ref Array

    [TestMethod]
    public void TestMethodRef1()
    {
      string[] astr = new string[] { "aaa" };
      ModifyArrayRef1(ref astr);
      Assert.AreEqual("bbb", astr[0]);
    }

    [TestMethod]
    public void TestMethodRef2()
    {
      //Ref array can change the array itself, like giving it a new length
      string[] astr = new string[] { "aaa" };
      ModifyArrayRef2(ref astr);
      Assert.AreEqual(2, astr.Length);
      Assert.AreEqual("ccc", astr[0]);
    }

    public static void ModifyArrayRef1(ref string[] astr)
    {
      astr[0] = "bbb";
    }

    public static void ModifyArrayRef2(ref string[] astr)
    {
      astr = new string[] { "ccc", "ccc" };
    }

   
#endregion


Living in Chicago and interested in working for a great company? Check out the careers at Paylocity.

tags:  

links: digg this    technorati