Last post Jun 09, 2011 04:09 AM by GPankaj
Jun 08, 2011 03:11 PM|Digitborn.com|LINK
I have code like:
PriceRange1 = (ArrayList)HttpContext.Current.Session["PriceRange1"];
for (int i = 0; i < PriceRange1.Count; i++)
PriceRange1[i] = (Convert.ToInt16(Convert.ToDouble(PriceRange1[i], System.Globalization.CultureInfo.CreateSpecificCulture("en-US"))) * ddlCurrency1).ToString();
The question is why in code like that, the session object HttpContext.Current.Session["PriceRange1"] is changing when the ArrayList object PriceRange is chaning? I've got the values from session into PriceRange1, then i want the session object to keep the
current values, how to do that?
Jun 08, 2011 03:22 PM|Jeev|LINK
its changing because all of them are reference types. If you do not want manipulations to affect that is in the session. you want to copy the session variable in a new arraylist and then manipulate it
ArrayList PriceRange1= new ArrayList((ArrayList)HttpContext.Current.Session["PriceRange1"]);
Jun 09, 2011 03:44 AM|Digitborn.com|LINK
ts changing because all of them are reference types.
I understand that. So, another ArrayList is another reference type, so:
If you do not want manipulations to affect that is in the session. you want to copy the session variable in a new arraylist and then manipulate it
what do you mean?
Jun 09, 2011 04:09 AM|GPankaj|LINK
This is a value type vs reference type question. A value type is a plain old data like int,strings. You pass a value type A to a function and the function modifies the value then it will have no impact on the original value of A unless the function marks
the parameter as either ref or out. This is because the value type is copied to a function-local variable during function invocation. A value type cannot be null. When you assign a value type instance to another instance
then it is a field-by-field copy. Once the assignment finishes each instance has a distinct copy of the data.
A reference type is anything that is not a value type. Specifically a reference type is any instance of a class or array. Reference types can be thought of as pointer to the actual object. When you assign a reference type instance to another instance
it is simply copying the pointer. Therefore both instances point to the same data. If you change the data through one instance then you'll see the changes in the other.
ArrayList is a class the instances are reference type instances. Assigning these instances simply involves copying the pointer.
As the pointer is copied to both any changes to one will be reflected in the other.
If you use the code provided by Jeev then the session elements are copied to the new list and that will resolve your issue.
Hope this helps.