Skip to content

Instantly share code, notes, and snippets.

@negativeeddy
Last active September 30, 2016 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negativeeddy/f39eb34333c3a7b9f0c65663fa75fcaf to your computer and use it in GitHub Desktop.
Save negativeeddy/f39eb34333c3a7b9f0c65663fa75fcaf to your computer and use it in GitHub Desktop.
This is how I do strongly typed application settings. Either pass the Dictionary in if provided by the system, or serialize/deserialize to disk as needed.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NegativeEddy.Settings
{
public class ApplicationSettings
{
Dictionary<string, object> _settingsBag;
public void Load()
{
// TODO: deserialize file into _settingsBag
}
public void Save()
{
// TODO: serialize _settingsBag to file
}
/// <summary>
/// Sample int property
/// </summary>
public int PreviewCount
{
get { return GetSetting(8); }
set { SetSetting(value); }
}
/// <summary>
/// Sample bool propety
/// </summary>
public bool ShowHelpOnLogin
{
get { return GetSetting(false); }
set { SetSetting(value); }
}
/// <summary>
/// Sample string property
/// </summary>
public string Token
{
get { return GetSetting(string.Empty); }
set { SetSetting( value); }
}
private T GetSetting<T>(T defaultVal, [CallerMemberName] string key = null)
{
if (_settingsBag.ContainsKey(key))
{
return (T)_settingsBag[key];
}
else
{
return defaultVal;
}
}
private void SetSetting<T>(T value, [CallerMemberName]string key = null)
{
_settingsBag[key] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment