Search code examples
c#xamaringenericsxamarin.formsxamarin.essentials

Xamarin.Essentials.Preferences set/get with generic type in Xamarin.Forms


public class PreferenceManager
{
    private static PreferenceManager _instance = null;
    private static readonly object _lock = new object();

    private PreferenceManager() { }
    public static PreferenceManager Instance
    {
        get
        {
            lock (_lock)
            {
                if (_instance == null)
                    _instance = new PreferenceManager();

                return _instance;
            }
        }
    }

    public void SetPreference<T>(string key, T value)
    {
        Preferences.Set(key, value);
    }
    public T GetPreference<T>(string key)
    {
        object value = Preferences.Get(key, null);
        return (T)Convert.ChangeType(value, typeof(T));
    }
}

I'd like to make wrapper class for manage all process about Xamarin.Essentials.Preferences.

There are so many overrides with different types for getting/setting in Essentials class.

So, I tried to change return value with generic and set value also, because I think it looks more simple.

But, there is an error in SetPreference method : cannot convert from 'T' to 'string'.

Is there any good solution for making wrapper class?

I want to handle all processes in here with one method.... :-(


Solution

  • According to Xamarin Essentials Preferences.shared.cs on Github, set method in Preferences doesn't support generic type. So we could not wrap it in a generic setter directly.

    And only seven data types are supported in Xamarin Preferences accoridng to Xamarin.Essentials: Preferences. I could only code for each data types like the following code:

    public void SetPreference<T>(string key,T value)
    {
        if (value is string)
        {
            Preferences.Set(key, Convert.ToString(value));              
        }
        if (value is double)
        {
            Preferences.Set(key, Convert.ToDouble(value));
        }
        ...
    }
    

    Hope it works for you.