Search code examples
c#windows-phone-8isolatedstorage

A change in one object changes the second one too


I'm creating two objects and assign them with a data from IsolatedStorage. But when I change one object the second one changes too. ( I think the problem may be the pointers are the same, but I can't solve it. )

private ArrayOfClsSimpleData lstUsers;
private ArrayOfClsSimpleData tmpLstUsers;

in class' globals

tmpLstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("users");
lstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("users");

The first status of the arrays:

Debug.Write(lstUsers.Count)

Output: 2

Debug.Write(tmpLstUsers.Count)

Output: 2

The counts are the same as expected. But, after I add an item to one list, the other list gets updated too and the counts are still same.

lstUsers.Add(new ArrayOfClsSimpleData());


Debug.Write(lstUsers.Count)

Output: 3

Debug.Write(tmpLstUsers.Count)

Output: 3


EDIT : IsolatedStorageHelper class is something to help to get objects, save object etc. that I do use for simplifying things, so just think it as getting objects from IsolatedStorage.

it is implemented like this:

 public static T GetObject<T>(string key)
    {
        if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
        {
            return (T)IsolatedStorageSettings.ApplicationSettings[key];  // return the object 
        }

        return default(T); // if key doesn't exists , return default object
    }

So it just gets it from IsolatedStorage. If you don't know isolated storage you can see it from here

So, how can I fix the code so that I can change one without changing the other?


Solution

  • So, basically lstUsers and tmpLstUsers are references to the same object. All you have to do is to create a new one and copy content from the original. If you need a quick solution, then you can do it like this (code below). I just guess that ArrayOfClsSimpleData is some kind of array.

    lstUsers = IsolatedStorageHelper.GetObject<ArrayOfClsSimpleData>("myKey");
    tmpLstUsers = new ArrayOfClsSimpleData();
    
    foreach (object user in lstUsers) // I don't know the type of objects in ArrayOfClsSimpleData, so I wrote 'object', but you should use the actual type
        tmpLstUsers.Add(user);