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!");
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)
throw
new ApplicationException("Unable
to find Parse method!");
value = (T)methodInfo.Invoke(null,
new object[] {
obj });
return (T)value;
}
}
return default(T);
}
Invoking the Method
The following code can be used to invoke the above method:
int
i = _util.GetValue<int>("123");
long
j = _util.GetValue<long>("abcd");
float
k = _util.GetValue<float>("100.01");
double
l = _util.GetValue<double>("200.20");
Point of Note
.Net Reflection is used to implement this method. I would like to say that in
case fast performance is required, this method is not advisable.