Syntax
Syntax

Reputation: 2197

C# Mono SharedPreferences|LocalSettings alternative

I am writing an app in Mono, it is a non-phone app we simply use it to target multiple platforms internally.

I am looking to persist simple application settings and am a big fan of the approach used by SharedPreferences in Android or LocalSettings on Windows platforms; does anyone know of a similar approach available in the Mono ecosystem?

Upvotes: 0

Views: 95

Answers (1)

SushiHangover
SushiHangover

Reputation: 74124

Mono supports System.Configuration.ApplicationSettingsBase (my favorite). You could also use .ini files, there is a Registry wrapper, etc...

Setting's Subclass:

class MySetting : System.Configuration.ApplicationSettingsBase
{
    [UserScopedSettingAttribute]
    [DefaultSettingValueAttribute("Overflow")]
    public String Stack
    {
        get { return (String)this["Stack"]; }
        set { this["Stack"] = value; }
    }
}

Usage:

class MainClass
{
    public static void Main(string[] args)
    {
        var settings = new MySetting();
        Console.WriteLine(settings.Stack); // Default value

        settings.Stack = "Not Overflowing"; // Assign new value
        settings.Save(); // Persist the setting's changes

        var settings2 = new MySetting(); // ReLoad persisted values
        Console.WriteLine(settings2.Stack);

        var settings3 = new MySetting(); // Reset values back to their defaults
        settings3.Reset();
        Console.WriteLine(settings3.Stack);
    }
}

macOS Output:

StackOverflow
Not Overflowing
StackOverflow

ref: https://github.com/mono/mono/blob/aa77a6ddccd9751a7f83fb066add7baabfb84062/mcs/class/System/System.Configuration/ApplicationSettingsBase.cs

Upvotes: 1

Related Questions