c# – Generics and nullable type – Stack Overflow
Posted by jpluimers on 2011/06/14
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






.NET/C#: refactoring some C# 1 code that uses HashTables as a poor mans property bag (via:Stack Overflow) « The Wiert Corner – irregular stream of stuff said
[…] problem was that I felt my code was convoluted, and should be denser, especially avoiding Convert.ChangeType. My code was already much simpler than casting tuples to a […]