I am working through the Windows 8 app tutorial. They have some code about savin
ID: 643371 • Letter: I
Question
I am working through the Windows 8 app tutorial.
They have some code about saving app data like so:
private void NameInput_TextChanged(object sender, TextChangedEventArgs e)
{
Windows.Storage.ApplicationDataContainer roamingSettings =
Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["userName"] = nameInput.Text;
}
I have worked with C# in the past and found that things like using constant string values (like "userName" in this case) for keys could get messy because auto-complete did not work and it was easy to forget if I had made an entry for a setting before and what it was called. So if I don't touch code for awhile I end up accidentally creating multiple entries for the same value that are named slightly differently.
Surely there is a better way to keep track of the strings that key to those values. What is a good solution to this problem?
Explanation / Answer
I would encapsulate it somehow. Maybe like this:
class Settings
{
Windows.Storage.ApplicationDataContainer roamingSettings;
public Settings()
{
roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
}
public String UserName {
get { return (String)roamingSettings.Values["userName"]; }
set { roamingSettings.Values["userName"] = value ;}
}
// etc..
}
The value is only in one place, so you can always check what you have already declared. It enables intellisense and it makes it type safe. You could also make the whole thing static or singleton.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.