How do I use DateTime.TryParse with a Nullable<DateTime>?
Solution 1:
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;
Solution 2:
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?)