Вопрос

I have a ViewState["blah"] that is a list of strings. At some point I set a List<string> variable to be equal to view state. Whatever change I make to this variable affects the view state:

List<string> a = {"1", "2", "3"};
ViewState["Blah"] = a;
....
List<string> b = (List<string>)ViewState["Blah"];
b.Remove("2");

Now, ViewState["Blah"] is {"1", "3"}. What am I doing wrong?

Это было полезно?

Решение

Because when you do

List<string> b = (List<string>)ViewState["Blah"];

You're assigning to b a pointer to a place in memory (a reference) and not a copy of the list. This means that b and ViewState["Blah"] points to the same list and changes on either of those affect the other.

You could clone your list if you want to detach b from your ViewState instance

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top