The Problem
Parsing strings into other objects using tryParse()
is a pain, and results in ugly code. I was sick and tired of seeing this kind of thing all over my projects:
var someStringThatShouldBeAnInt = "10";
int i = 0;
if(int.TryParse(someStringThatShouldBeAnInt, out i))
{
}else
{
}
The Desired Solution
Abstract this ugliness and replace it with something like this:
var someStringThatShouldBeAnInt = "10";
var i = someStringThatShouldBeAnInt.Parse<int>();
The How
Seems like if I could dynamically call the tryParse()
using Reflection I could write this once for every type that has the tryParse()
available to it.
public static T Parse<T>(this string thingToParse)
{
var retType = typeof(T);
var tParse = retType.GetMethod("TryParse",
BindingFlags.Public | BindingFlags.Static, null,
new[] { typeof(string), retType.MakeByRefType() }, null);
if (tParse != null)
{
var parameters = new object[] { thingToParse, null };
var success = (bool)tParse.Invoke(null, parameters);
if (success)
{
return (T)parameters[1];
}
}
return default(T);
}
What If the type you are converting to doesn't implement tryParse()?
var csv = "1,2,3,4,5,6,7";
var list = csv.Parse<List<string>>();
Yea that’s not going to work. So let's give you the option to pass in your own converter.
public static T Parse<T>(this string thingToParse, Func<string, T> parser)
{
return parser.Invoke(thingToParse);
}
Wow that’s even cleaner. Now we can do the following:
var csv = "1,2,3,4,5,6,7";
var list = csv.Parse<List<string>>(x => x.Split(',').ToList());
Yea that’s clean.
If you find this useful or see ways to improve please feel free to comment.
You can also find some other great topics over at my blog at: http://www.sympletech.com.
This utility can be found with many others here: https://github.com/sympletech/SympleLib.