Safer reading of dictionary values

This commit is contained in:
Matt Nadareski
2023-08-14 23:23:57 -04:00
parent ed1f809065
commit 3d99cf828f

View File

@@ -11,11 +11,20 @@ namespace SabreTools.Models.Internal
/// Read a key as the specified type, returning null on error
/// </summary>
public T? Read<T>(string key)
{
try
{
if (!ValidateKey(key))
return default;
if (this[key] is not T)
return default;
return (T?)this[key];
}
catch
{
return default;
}
}
/// <summary>
/// Read a key as a bool, returning null on error
@@ -25,7 +34,7 @@ namespace SabreTools.Models.Internal
if (!ValidateKey(key))
return null;
bool? asBool = Read<bool>(key);
bool? asBool = Read<bool?>(key);
if (asBool != null)
return asBool;
@@ -46,7 +55,7 @@ namespace SabreTools.Models.Internal
if (!ValidateKey(key))
return null;
double? asDouble = Read<double>(key);
double? asDouble = Read<double?>(key);
if (asDouble != null)
return asDouble;
@@ -66,7 +75,7 @@ namespace SabreTools.Models.Internal
if (!ValidateKey(key))
return null;
long? asLong = Read<long>(key);
long? asLong = Read<long?>(key);
if (asLong != null)
return asLong;