Dela via


Xamarin.Essentials: Preferences

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 check if a given key exists in preferences:

bool hasKey = Preferences.ContainsKey("my_key");

To remove the key from preferences:

Preferences.Remove("my_key");

To remove all preferences:

Preferences.Clear();

Tip

The above methods take in an optional string parameter called sharedName. This parameter is used to create additional containers for preferences which are helpful in some use cases. One use case is when your application needs to share preferences across extensions or to a watch application. Please read the platform implementation specifics below.

Supported Data Types

The following data types are supported in Preferences:

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

Integrate with System Settings

Preferences are stored natively, which allows you to integrate your settings into the native system settings. Follow the platform documentation and samples to integrate with the platform:

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, otherwise 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, with the exception being apps that target and run on Android 6.0 (API level 23) or later that use 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

Find more Xamarin videos on Channel 9 and YouTube.