0

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;
}
anar khalilov
  • 16,993
  • 9
  • 47
  • 62
  • 2
    See http://stackoverflow.com/questions/2961656/generic-tryparse – mbdavis Apr 17 '15 at 11:14
  • @mbdavis, converter.ConvertFromString(input) is very primitive. For example you cannot specify date format. – anar khalilov Apr 17 '15 at 13:04
  • I don't think you can make many modifications that make any sense if you want that level of control. They are very small chunks of code anyway, what redundancies do you see? You could use interfaces to define a parse method for different objects that could convert types to nullables but it would leave you with more code than you had originally... – mbdavis Apr 17 '15 at 13:13

1 Answers1

1

See provided example. This is just one of multiple ways, in the end it depends on your expected data types.

You should definitely include error handling to this.

public void Test()
{
    Console.WriteLine(Parse<int>("1"));
    Console.WriteLine(Parse<decimal>("2"));
    Console.WriteLine(Parse<DateTime>("2015-04-20"));
}

public static T Parse<T>(string input)
{
    TypeConverter foo = TypeDescriptor.GetConverter(typeof(T));
    return (T)(foo.ConvertFromInvariantString(input));
}
Michael Sander
  • 2,677
  • 23
  • 29
  • http://coding.grax.com/2013/04/generic-tryparse.html Here is a blog post I did on a generic TryParse that is similar to this. – Grax32 Apr 17 '15 at 15:04