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 = 
            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?

  • you can use an enum for that is the possible values are finite – ratchet freak Oct 6 '12 at 23:14
  • or maybe static constant strings? – rwong Oct 6 '12 at 23:55

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.

| improve this answer | |
  • +1. Also, it makes it easier to change the language - Engrish ain't universal. – CAD bloke Jul 8 '17 at 6:19

It may depend on the speed and memory performance that you need.

I have been thinking a lot about radix sort recently. It has some great characteristics. It could be a great candidate for anything where you might want to implement your own auto complete. Speed wise it is O(kN) complexity where k is the length of the strings and N is the number of strings. Storage is also O(kN).

Unlike a STL vector, a linked list, or an array of strings, maintaining a sorted table does not involve a linear search for an insertion point because the data is in a tree with branches that are indexed by the letters in the string which is a constant time operation repeated once for each character in the string. Checking to see if a string is in the table takes the same or less effort, terminating when one of the letters indexes a NULL pointer. Finding the first M strings to display for an auto complete is similarly fast.

A hash table can also be a great tool for dictionary lookup.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.