Xamarin.Essentials: Preferences

Pre-release NuGet

The Preferences class helps to store application preferences in a key/value store.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

Using Preferences

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

To save a value for a given key in preferences:

Preferences.Set("my_key", "my_value");

To retrieve a value from preferences or a default if not set:

var myValue = Preferences.Get("my_key", "default_value");

To remove the key from preferences:

Preferences.Remove("my_key");

To remove all preferences:

Preferences.Clear();

In addition to these methods each take in an optional sharedName that can be used to create additional containers for preference. Read the platform implementation specifics below.

Supported Data Types

The following data types are supported in Preferences:

  • bool
  • double
  • int
  • float
  • long
  • string
  • DateTime

Implementation Details

Values of DateTime are stored in a 64-bit binary (long integer) format using two methods defined by the DateTime class: The ToBinary method is used to encode the DateTime value, and the FromBinary method decodes the value. See the documentation of these methods for adjustments that might be made to decoded values when a DateTime is stored that is not a Coordinated Universal Time (UTC) value.

Platform Implementation Specifics

All data is stored into Shared Preferences. If no sharedName is specified the default shared preferences are used, else the name is used to get a private shared preferences with the specified name.

Persistence

Uninstalling the application will cause all Preferences to be removed. There is one exception to this, which for apps that target and run on Android 6.0 (API level 23) or later that are using Auto Backup. This feature is on by default and preserves app data including Shared Preferences, which is what the Preferences API utilizes. You can disable this by following Google's documentation.

Limitations

When storing a string, this API is intended to store small amounts of text. Performance may be subpar if you try to use it to store large amounts of text.

API