Summary
In this article I am going to explain how to create a generic method named
GetValue() that can parse int, float, long, double data types. The method would
parse any value objects passed through it and prevents throwing errors in case
of invalid data. When invalid data is passed the method will return the default
value of type passed.
Code Detailed
The int, long, float and double data types contains TryParse() and Parse() methods in common which are static. Our GetValue() method takes the object to be parsed and identifies the return type through Generic Argument T.
In case of errors like the TryParse or Parse methods are missing in the type T,
an exception is thrown. In case of errors data errors like argument is null or
invalid data the default(T) would be returned.
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)
throw new
ApplicationException("Unable
to find TryParse method!");

Mark LyonsPosted Aug 22, 2021, 10:51 AM
This will not run with nullable types.
Evgeny NibylicinPosted Apr 10, 2014, 5:59 AM
public static T GetValue<T>(object value, T defaultValue) { T result = default(T); try { result = (T)Convert.ChangeType(value, typeof(T)); } catch { result = defaultValue; } return result; }
Lajapathy ArunPosted May 6, 2012, 1:50 AM
Could you have any article to read about the reflection to use wisely? It will be useful
Jean PaulPosted May 5, 2012, 12:19 PM
Hi Arun.. Thank Your for your attention. One thing to update: Reflection is 8 times slower than normal code. But computer is faster than that. So please use it wisely in the right situation.
Lajapathy ArunPosted May 4, 2012, 11:44 AM
Thanks something good to see