I need to write methods that take a string value and try to parse it as a primitive data type. If parsing is not successful, the methods should return null.
I have written the following methods but I feel there must be a way to decrease redundancy. I know about generics but since parsing is different for each data type, using generics seems complicated.
How can one improve the following code?
public static DateTime? GetNullableDateTime(string input)
{
DateTime returnValue;
bool parsingSuccessful = DateTime.TryParseExact(input, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out returnValue);
return parsingSuccessful ? returnValue : (DateTime?)null;
}
public static decimal? GetNullableDecimal(string input)
{
decimal returnValue;
bool parsingSuccessful = decimal.TryParse(input, out returnValue);
return parsingSuccessful ? returnValue : (decimal?)null;
}