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?
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.
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 .
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With