It would be impossible to use generics so that I don't have so much redundant code?
You could do it with reflection, but it would be relatively slow. Otherwise, you could create a map from type to "method to use for this type", but that would be pretty ugly. Among other things, it will never be truly general - it will only work for types that provided the TryParse method for proper signature, which could not be known at compile time.
I would personally think about changing signatures and behavior, by the way. Currently, although the value type is NULL, it will never have a null value at the end of the method, even if you return false . Why not make the return value the result of a parsing operation, returning null on error?
protected static long? TryParseInt64(string input) { long outValue; return Int64.TryParse(input, out outValue) ? (long?) outValue : null; }
source share