Search code examples
c#windows-phone-7isolatedstorage.nettrygetvalue

Not sure why I'm getting an InvalidCastException


I am getting an InvalidCastException and I don't understand why.

Here is the code that raises the exception:

public static void AddToTriedList(string recipeID)
{
    IList<string> triedIDList = new ObservableCollection<string>();
    try
    {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        if (!settings.Contains("TriedIDList"))
        {
            settings.Add("TriedIDList", new ObservableCollection<Recipe>());
            settings.Save();
        }
        else
        {
            settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);
        }
        triedIDList.Add(recipeID);
        settings["TriedIDList"] = triedIDList;
        settings.Save();
    }
    catch (Exception e)
    {
        Debug.WriteLine("Exception while using IsolatedStorageSettings in AddToTriedList:");
        Debug.WriteLine(e.ToString());
    }
}

AppSettings.cs: (extract)

// The isolated storage key names of our settings
const string TriedIDList_KeyName = "TriedIDList";

// The default value of our settings
IList<string> TriedIDList_Default = new ObservableCollection<string>();

...

/// <summary>
/// Property to get and set the TriedList Key.
/// </summary>
public IList<string> TriedIDList
{
    get
    {
        return GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default);
    }
    set
    {
        if (AddOrUpdateValue(TriedIDList_KeyName, value))
        {
            Save();
        }
    }
}

GetValueOrDefault<IList<string>>(TriedIDList_KeyName, TriedIDList_Default) and AddOrUpdateValue(TriedIDList_KeyName, value) are the usual methods recommended by Microsoft; you can find the full code here.

EDIT: I got exception in this line:

settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);

Solution

  • You're adding a ObservableCollection<Recipe> to your settings:

    settings.Add("TriedIDList", new ObservableCollection<Recipe>());
                                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
    

    But then you're reading back a IList<string>, which is quite obviously a different type:

    settings.TryGetValue<IList<string>>("TriedIDList", out triedIDList);
                      // ^^^^^^^^^^^^^
    

    Your declaration of triedIDList looks like this:

       IList<string> triedIDList = new ObservableCollection<string>();
    // ^^^^^^^^^^^^^                // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    As a start, decide on one type and then use the exact same type in all these places (even if you think it's not strictly necessary), then see if the InvalidCastException goes away.