The given snippet do not work with 'bool' for example, as the 'default(T)' is a perfectly valid value.
Here is a working bit of code:
/// <summary>
/// Load a data, and save it with the default value if it isn't found
/// </summary>
/// <typeparam name="T">The type of the data</typeparam>
/// <param name="Key">The name of the data</param>
/// <param name="DefaultValue">The default value</param>
/// <returns>The loaded value if found, the default value otherwise</returns>
static public T LoadOrCreate<T>(String Key, T DefaultValue)
{
if (ES3.KeyExists(Key))
return ES3.Load<T>(Key, DefaultValue);
ES3.Save<T>(Key, DefaultValue);
return DefaultValue;
}
/// <summary>
/// Load a data, and save it with the default value if it isn't found
/// </summary>
/// <typeparam name="T">The type of the data</typeparam>
/// <param name="this_">The 'ES3File' object</param>
/// <param name="Key">The name of the data</param>
/// <param name="DefaultValue">The default value</param>
/// <returns>The loaded value if found, the default value otherwise</returns>
static public T LoadOrCreate<T>(this ES3File this_, String Key, T DefaultValue)
{
if (this_.KeyExists(Key))
return this_.Load<T>(Key, DefaultValue);
this_.Save<T>(Key, DefaultValue);
return DefaultValue;
}
/// <summary>
/// Open a file, create it if it does not exists
/// </summary>
/// <param name="FileName">The file name</param>
/// <returns>The file</returns>
static public ES3File OpenOrCreate(String FileName)
{
if (!ES3.FileExists(FileName))
{ // File not found, create an empty one
ES3Writer ConfigWriter = ES3Writer.Create(FileName, QGlobal.TheES3Settings);
ConfigWriter.Save(true);
ConfigWriter.Dispose();
}
return new ES3File(FileName, true);
}
I also put a 'OpenOrCreate()' as it is very similar.
Note that if it were done directly in ES3, then we could avoid getting twice the key, because if it exists the result could be remembered and reused to load the current value, so it would be more optimized.