I am trying to implement a generic method for values that provide Parse
and ParseExact
methods. Types for which my method should work, are value types (like double
, int
etc.) and TimeSpan
.
Any ideas how I can implement what I describe?
To understand better what I need, I made some code that roughly depicts what I would like to achieve (obviously it doesn't work). Flags
is just some enum
.
public Dictionary<Flags, object> FlagValues { get; } = new Dictionary<Flags, object>();
public T GetFlagValue<T>(Flags flag, string formatString = null) where T : struct
{
T result = default(T);
if (FlagValues.TryGetValue(flag, out object flagValueRaw))
{
if (formatString == null)
{
result = T.Parse(flagValueRaw, CultureInfo.InvariantCulture);
}
else
{
result = T.ParseExact(flagValueRaw, formatString, CultureInfo.InvariantCulture);
}
}
return result;
}