In my opinion whenever you need to parse a value you should always use the TryParse method to make your code more robust and able to handle errors better. The draw back to this is you and up writing a lot of if else statements. I got tired of doing this so was trying to find a more abstracted way to do this for all my values. I found this bit of code very handy. So far it has worked great!
public T GetValue<T>(object obj)
{
if (obj != null)
{
Type type = typeof(T);
T value = default(T);
var methodInfo = (from m in type.GetMethods(BindingFlags.Public | BindingFlags.Static)
where m.Name == "TryParse"
select m).FirstOrDefault();
if (methodInfo == null)
return default(T);
object result = methodInfo.Invoke(null, new object[] { obj, value });
if ((result != null) && ((bool)result))
{
methodInfo = (from m in type.GetMethods(BindingFlags.Public | BindingFlags.Static)
where m.Name == "Parse"
select m).FirstOrDefault();
if (methodInfo == null)
return default(T);
value = (T)methodInfo.Invoke(null, new object[] { obj });
return (T)value;
}
}
return default(T);
}
Comments