Skip to content

Instantly share code, notes, and snippets.

@lolp1
Created June 23, 2016 01:06
Show Gist options
  • Save lolp1/a4065121a747de3fcd15331f797de6aa to your computer and use it in GitHub Desktop.
Save lolp1/a4065121a747de3fcd15331f797de6aa to your computer and use it in GitHub Desktop.
Dictionary Ini
public static class DictionaryExtensions
{
public static void AddItem<T>(this Dictionary<string, object> dictionary, string key, T value)
{
if (!dictionary.ContainsKey(key))
{
dictionary[key] = value;
return;
}
throw new Exception("The dictionary already contains the key: " + key);
}
public static T GetItem<T>(this Dictionary<string, object> dictionary, string key)
{
if (dictionary.ContainsKey(key))
{
return dictionary[key].RequireType<T>();
}
throw new KeyNotFoundException("The dictionary does not contain the key: " + key);
}
}
public static class Example
{
public static void RunIniExample()
{
var ini = new Ini();
ini.Write("Display", "UseWindowMode", false);
var section = ini.GetSection("Display");
section.Write("UseVsync", false);
section.Write("Width", 500);
section.Write("Height", 500);
var json = new JsonSettings<Ini>(ini);
json.Save();
json.Current = null;
json.Load();
var iniFromFile = json.Current;
var displaySection = iniFromFile.GetSection("Display");
var h = displaySection.Read<int>("Height");
var w = displaySection.Read<int>("Width");
Console.WriteLine($"Height: {h} Width {w}.");
}
}
public class Ini
{
private readonly Dictionary<string, Dictionary<string, object>> _sections =
new Dictionary<string, Dictionary<string, object>
>();
public IReadOnlyDictionary<string, Dictionary<string, object>> Sections => _sections;
public void Write<T>(string section, string key, T value)
{
if (!_sections.ContainsKey(section))
{
_sections.Add(section, new Dictionary<string, object>());
}
_sections[section].AddItem(key, value);
}
public T Read<T>(string section, string key)
{
if (!_sections.ContainsKey(section))
{
throw new Exception($"The section: {section} was not found in the ini.");
}
return _sections[section].GetItem<T>(key);
}
public IniSection GetSection(string section)
{
return new IniSection(section, this);
}
}
public class IniSection
{
private readonly Ini _iniDictionary;
public readonly string Section;
public IniSection(string section, Ini iniDictionary)
{
Section = section;
_iniDictionary = iniDictionary;
}
public void Write<T>(string key, T value)
{
_iniDictionary.Write(Section, key, value);
}
public T Read<T>(string key)
{
return _iniDictionary.Read<T>(Section, key);
}
}
public static class ObjextExtensions
{
public static T RequireType<T>(this object @object)
{
if (!(@object is T))
{
throw new InvalidCastException("RequireType<T> cast");
}
return (T)@object;
}
public static T As<T>(this object @object)
{
return @object.RequireType<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment