I have a ViewState
holding a List<T>
public List<AwesomeInt> MyList
{
get { return ((List<int>)ViewState["MyIntList"]).Select(i => new AwesomeInt(i)).ToList(); }
set { ViewState["MyIntList"] = value.GetIntegers(); }
}
Now, when I call MyList.Add(new AwesomeInt(3))
let's say, the list does not persist the change.
I believe this is because the .ToList()
in the get
is creating a new List object and therefore the set
will never be called, thus never saving in ViewState.
I have worked around this problem before by either
- not calling
.Select/.ToList()
by saving/calling directly without a conversion. - not using the
.Add
or.Remove
functions and instead re-initializing theList
with an equals.
However sometimes 1.
is impractical if the class is not serializable and I have no control over that, and 2.
is kind of ugly because I have to copy it to a temp first, then add, then re-assign, or play around with Concat
to add a single item.
Is there a better way of doing this?