I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:
DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d);
the compiler tells me
'out' argument is not classified as a variable
Not sure what I need to do here. I've also tried:
out (DateTime)d.Value
and that doesn't work either. Any ideas?
DateTime itself is a value type. It cannot be null.
The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
TryParse(String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true if the conversion was successful and false if otherwise.
As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:
public static DateTime? TryParse(string text) { DateTime date; if (DateTime.TryParse(text, out date)) { return date; } else { return null; } }
... or if you like the conditional operator:
public static DateTime? TryParse(string text) { DateTime date; return DateTime.TryParse(text, out date) ? date : (DateTime?) null; }
Or in C# 7:
public static DateTime? TryParse(string text) => DateTime.TryParse(text, out var date) ? date : (DateTime?) null;
DateTime? d=null; DateTime d2; bool success = DateTime.TryParse("some date text", out d2); if (success) d=d2;
(There might be more elegant solutions, but why don't you simply do something as above?)
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