Would it not be possible to use generics so that I don't need to have so much redundant code?
You could do it with reflection, but that would be relatively slow. Otherwise, you could create a map from type to "method to use for that type" but it would be pretty ugly. Aside from anything else, it would never be truly generic - it would only work for types that provided a TryParse
method of the right signature, which couldn't be known at compile-time.
I would personally consider changing the signature and behaviour, by the way. Currently even though the type of value
is nullable, it will never have the null value at the end of the method, even if you return false
. Why not make the return value the result of the parsing operation, returning null
on failure?
protected static long? TryParseInt64(string input)
{
long outValue;
return Int64.TryParse(input, out outValue) ? (long?) outValue : null;
}