IsolatedStorageSettings extension method

Written on February 3, 2011

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> /// The System.Type of the value parameter. /// </param> /// The key of the value to get.</param> /// A value to return if the key is not found.</param> /// When this method returns, the value associated with the specified key if the key is found; /// otherwise, the value of . public static T TryGetValue(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.

Categories: DotNet, Windows Phone