A while ago, I needed some generic way of parsing data that could result instancef of both regular ordinal and nullable ordinal types.
Luckily there was a nice question about this on StackOverflow, of which I liked this answer (source code below) much more than the accepted answer: concise, elegant, period.
public static T? Parse(this string text) where T: struct
{
object o = null;
try
{
var ttype = typeof(T);
if (ttype.IsEnum)
{
T n = default(T);
if (Enum.TryParse(text, true, out n))
return n;
}
else
o = Convert.ChangeType(text, ttype);
}
catch { }
if (o == null)
return new Nullable();
return new Nullable((T)o);
}
–jeroen





