Generic type parser using Generics C# .NET
Recently I had the need to safely parse multiple types from text ignoring exceptions. Microsoft did not implement an IParsable interface (despite requests) so I thought a solution was crying out for using generics.
The concept was simple: pass in an object of type T and call T.Parse. The .NET compiler can check at compile time that the type supports Parse, right? Unfortunately not. Although generics allows constraints such as new(), it does not support arbitrary method constraints.
Lack of method constraints means attempting to call T.Parse won't work. The result is having to use reflection to get around this. Of course passing in a type that does not support Parse will throw an exception, but by virtue of the design this will be handled and the type will return the default.
private T SafeParseAndAssign<T>(string val)
where T : new()
{
try
{
T ValOut = new T();
MethodInfo MI = ValOut.GetType().
GetMethod("Parse", new Type[] { val.GetType() });
return (T)MI.Invoke(ValOut, new object[] { val });
}
catch
{
// swallow exception
}
return default(T);
}

0 Comments:
Post a Comment
<< Home