IsolatedStorageSettings extension method
I noticed that my Windows Phone 7 applications started to have lots of these kinds of statements in the OnLaunch and OnActivate event handlers:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; bool allowLocationService; AllowLocationServiceProperty = settings.TryGetValue( “AllowLocationService”, out allowLocationService ) ? allowLocationService : false;
I came up with simple this extension method to reduce the repetition:
/// <summary>
/// Gets a value for the specified key
/// </summary>
/// <typeparam name="T">The System.Type of the value parameter.</typeparam>
/// <param name="settings"></param>
/// <param name="key">The key of the value to get.</param>
/// <param name="default">A value to return if the key is not found.</param>
/// <returns>When this method returns, the value associated with the specified key if the key is found;
/// otherwise, the value of <paramref name="default"/>. </returns>
public static T TryGetValue<T>(this IsolatedStorageSettings settings, string key, T @default)
{
T value;
return settings.TryGetValue( key, out value ) ? value : @default;
}
Which means I can now do:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
AllowLocationServiceProperty = settings.TryGetValue( "AllowLocationService", false );
That’s a bit better!
There’s a few other examples in this thread in the Windows Phone 7 forums.