The Preferences class helps to store application preferences in a key/value store.
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.
Add a reference to Xamarin.Essentials in your class:
To save a value for a given key in preferences:
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:
To remove all preferences:
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:
Integrate with System Settings
Preferences are store natively, which allows you to integrate your settings into the native system settings. Follow the platform documetnation and samples to integrate with the platform:
- Apple: Implementing an iOS Settings Bundle
- iOS Applicaton Preferences Sample
- watchOS Settings
- Android: Getting Started with Settings Screens
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.
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.
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.