I'm trying to code a generic struct to parse nullable types.
I have several problems:
I can't inherit
Nullable<T>
cause it's a struct:public struct NullableParsable<T> : Nullable<T> where T : struct { }
Type T in interface list is not an interface
So I try with:
public struct NullableParsable<T> where T : struct
{
public static T? Parse(string s)
{
T? result = null;
string tName = typeof(T).Name;
switch(tName)
{
case "Int32": result = string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s); break;
case "Decimal": result = string.IsNullOrEmpty(s) ? null : (decimal?)decimal.Parse(s); break;
default: throw new NotImplementedException("unmanaged type: "+ tName);
}
return result;
}
}
I can't cast
int
toT
orint?
toT?
.I would like a simple way to switch among struct types (maybe an enum), for the moment I switch among type names
typeof(T).Name
. Or maybe a reflection mecanism to invokeParse
...
See complete code in this fiddle: https://dotnetfiddle.net/x6kHzx
Any idea of how to properly implement this functionality?