Hi I found this function in a utilities code file:
Version 1:
public static bool IsValidLong(string strLong)
{
bool result = true;
try
{
long tmp = long.Parse(strLong);
}
catch (Exception ex)
{
result = false;
}
return result;
}
I want to replace this (and validators for other types) with following:
Version 2:
public static bool IsValidLong(string strLong)
{
long l;
return long.TryParse(strLong, out l);
}
which version is better and why?
The first exists because the 2nd didn’t at one point (
Int64.TryParse()was added in .Net 2.0)…use the second version, why not take advantage of the features the framework adds in the newer releases if they’re available to you? 🙂The second is much clearer, leaner and more maintinable…I’d say it’s a much better approach… it just wasn’t available before.
Also, I believe
TryParse()doesn’t actually throw any exception internally, so it would be slower in a successful parse, but much quicker/less expensive than throwing an exception in the case of a failed parse.