jesh Posted October 8, 2007 Share Posted October 8, 2007 Can anyone explain to me why the following code produces what it is producing on my computer?This is the code - very straight forward stuff, as far as I'm concerned: using System;using System.Collections;using System.Text;using System.Web.UI;public partial class _Default : Page{ protected void Page_Load(object sender, EventArgs e) { ArrayList localArrayList = new ArrayList(); Hashtable localHashtable = new Hashtable(); string localString = String.Empty; StringBuilder localStringBuilder = new StringBuilder(); int localInteger = 0; for (int i = 0; i < 10; i++) { TestMethod(i, localHashtable, localArrayList, localString, localStringBuilder, localInteger); } Response.Write("Hashtable has " + localHashtable.Count + " elements.<br />"); Response.Write("ArrayList has " + localArrayList.Count + " elements.<br />"); Response.Write("String is '" + localString + "'.<br />"); Response.Write("StringBuilder is '" + localStringBuilder.ToString() + "'.<br />"); Response.Write("Integer is " + localInteger + ".<br />"); } private void TestMethod(int i, Hashtable testHashtable, ArrayList testArrayList, string testString, StringBuilder testStringBuilder, int testInteger) { testHashtable.Add(i, i); testArrayList.Add(i); testString += i + " "; testStringBuilder.Append(i + " "); testInteger += i; }} Here is the expected output: Hashtable has 0 elements.ArrayList has 0 elements.String is ''.StringBuilder is ''.Integer is 0.Yet, here is the actual output.Hashtable has 10 elements.ArrayList has 10 elements.String is ''.StringBuilder is '0 1 2 3 4 5 6 7 8 9 '.Integer is 0.Has anyone experienced this? Any explanations you can offer? Link to comment Share on other sites More sharing options...
jesh Posted October 8, 2007 Author Share Posted October 8, 2007 Bah! Always answering my own questions:http://msdn.microsoft.com/library/default....dParameters.aspI didn't make the connection that when you pass reference types - like Hashtables, ArrayLists, etc. - to methods, a copy of that reference is passed and, unless you change the reference to have it point to a different location, any changes you make to the parameter affect the original variable. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.