So I got sick of several things about the way TryParse works. I implemented a generic ParseOrDefault function using reflection. It appears to work as expected, but I'm not fool enough to say my code is bullet proof. What's wrong with it? If something is wrong with it, can it be fixed, or should this idea be tossed?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
Console.WriteLine(("true").ParseOrDefault<bool>());
Console.WriteLine(("false").ParseOrDefault<bool>());
Console.WriteLine(("23").ParseOrDefault<int>());
Console.WriteLine(("52").ParseOrDefault<int>());
Console.WriteLine(("4/22/1989").ParseOrDefault<DateTime>());
Console.WriteLine(("4/22/2016").ParseOrDefault<DateTime>());
}
}
public static class DataProcessAbstractionExtensions
{
public static T ParseOrDefault<T>(this string Value)
{
T ReturnedValue = default(T);
//Since C# doesn't impliment an IParsable interface to filter generically
//Reflection must be used to determine if object is in fact parsable
var type = typeof(T);
var MethodInfo = type.GetMethods().FirstOrDefault(MI =>
{
ParameterInfo[] ArgInfo = MI.GetParameters();
return (ArgInfo.Length == 2 && ArgInfo[0].ParameterType == typeof(string) && ArgInfo[1].IsOut && ArgInfo[1].ParameterType.GetElementType() == type);
});
if (MethodInfo != null && MethodInfo.IsStatic)
{
object[] Arguments = new object[] { Value, ReturnedValue };
MethodInfo.Invoke(null, Arguments);
return (T)Arguments[1];
};
return default(T);
}
}