Skip to content

Instantly share code, notes, and snippets.

@liebki
Created July 23, 2023 10:48
Show Gist options
  • Save liebki/98b8513d9fba8686f79453b812d52e05 to your computer and use it in GitHub Desktop.
Save liebki/98b8513d9fba8686f79453b812d52e05 to your computer and use it in GitHub Desktop.
Alternative to Session- and Localstorage on MAUI-Blazor
public class PreferencesStoreClone
{
/// <summary>
/// Store an element using any kind of key (if it doesnt exist)
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set(string key, object value)
{
string keyvalue = JsonConvert.SerializeObject(value);
if (keyvalue != null && !string.IsNullOrEmpty(keyvalue))
{
Preferences.Set(key, keyvalue);
}
}
/// <summary>
/// Get an element using a certain key, with type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T Get<T>(string key)
{
T UnpackedValue = default;
string keyvalue = Preferences.Get(key, string.Empty);
if (keyvalue != null && !string.IsNullOrEmpty(keyvalue))
{
UnpackedValue = JsonConvert.DeserializeObject<T>(keyvalue);
}
return UnpackedValue;
}
/// <summary>
/// Delete an element with a certain key
/// </summary>
/// <param name="key"></param>
public void Delete(string key)
{
Preferences.Remove(key);
}
/// <summary>
/// Check if an element with a certain key exists
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Exists(string key)
{
return Preferences.ContainsKey(key);
}
/// <summary>
/// ATTENTION: Clears the whole Preferences-Store
/// </summary>
public void ClearAll()
{
Preferences.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment