Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse to a nullable type

I would like to try to parse a string as a DateTime?, and if it fails then set the value to null. The only way I can think to do this is the following, but it doesn't seem very neat.

DateTime temp;
DateTime? whatIActuallyWant = null;
if (DateTime.TryParse(txtDate.Text, out temp)) whatIActuallyWant = temp;

Is this the only way?

like image 387
James Avatar asked Oct 06 '11 02:10

James


People also ask

What does TryParse mean?

TryParse(String, NumberStyles, IFormatProvider, Int32) Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What is difference between parse and TryParse?

The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .

What does TryParse return if successful?

public static bool TryParse (string value, out bool result); Parameters: value: It is a string containing the value to convert. result: When this method returns, if the conversion succeeded, contains true if value is equal to TrueString or false if value is equal to FalseString.

What is TryParse C #?

TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.


2 Answers

How about this:

DateTime? whatIActuallyWant = DateTime.TryParse(txtDate.Text, out temp) ? (DateTime?)temp : null;

You get a one-liner out of this (unfortunately need the DateTime? cast otherwise won't compile) - but personally I would probably stick to the null initialization and the subsequent if - it's just easier to read.

like image 171
BrokenGlass Avatar answered Oct 13 '22 16:10

BrokenGlass


If your going to be performing this operation more than once then I recommend adding a simple extension method for ease of use...

public static class Extensions
{
    public static DateTime? ToDateTime(this string val)
    {
        DateTime temp;
        if (DateTime.TryParse(val, out temp))
            return temp;
        else 
            return null;
    }
}

Which you can then use very easily...

DateTime? ret1 = "01/01/2011".ToDateTime();
DateTime? ret2 = myString.ToDateTime();
like image 34
Phil Wright Avatar answered Oct 13 '22 17:10

Phil Wright