Rahul Ranjan
Rahul Ranjan

Reputation: 1058

List reference issue c#

I have a list say listOriginal and am storing it in Viewstate..

ViewState["Origion"] = listPatientEncounter;

now,I need to do some formatting in the list items and save it on another Viewstate for further usage..

 List<....> listCopy = new List<....>();
 listCopy= (from n in listOriginal select n).ToList();

 //This method formattes a few listCopy items
   ViewState["copylist"] = ConverttoUTCTime(listCopy);

But,the problem is that the changes made in second list also shows op on the first list due to which I am getting problems where I want to use ViewState["Origion"] which has items in it's origional state..

Upvotes: 2

Views: 314

Answers (4)

Luis Tellez
Luis Tellez

Reputation: 2973

Objects will be passed by ref, you will need to copy the data inside the list to the second list, you cant use the .ToList().

You need to clone the items insisde your original list, and add them to the second one, you can manually copy values or use the Clone() if its available.

Upvotes: 3

Eric
Eric

Reputation: 401

Because you are using in-process Session state, the 2 lists are actually referencing the same instance of the list. You would need to clone your list in order to truely have 2 distinct lists.

Now, if you were using SQL session management, this would essentially end up performing the cloning for you, and they would be distinct since it would be serializing/deserializing the objects to a database.

Upvotes: 0

Warr
Warr

Reputation: 118

If item of list is an object, than you changed properties of a source object. .ToList() is creating new list object and it is not cloning the items.

In another words it will be the "another" list with the same items.

To resolve the issue you should clone list items.

Upvotes: 5

Tigran
Tigran

Reputation: 62256

This because (most probably) at least according to the result you get, it the content of your list is a reference type.

Having reference type filled inside one instance of the list and moved into another does not make it another instance. It cotinues to be (yes different pointer, but..) pointing to the same memory location. So the different lists elements points to the same location, so the changes made by one are visible by another.

To resolve this issue, one of possible solutions is creating a clone of your object, or at least, only those objects that you're going to change, if the change has not be affected in original collection by software architecture. This is just an idea, you should pick a solution that fits your needs.

Upvotes: 2

Related Questions