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.
You can't because Nullable<DateTime>
is a different type to DateTime
.
You need to write your own function to do it,
public bool TryParse(string text, out Nullable<DateTime> nDate)
{
DateTime date;
bool isParsed = DateTime.TryParse(text, out date);
if (isParsed)
nDate = new Nullable<DateTime>(date);
else
nDate = new Nullable<DateTime>();
return isParsed;
}
Hope this helps :)
EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.
P.S. The Bad Hoor in question is an old friend :)
I don't see why Microsoft didn't handle this. A smart little utility method to deal with this (I had the issue with int, but replacing int with DateTime will be the same effect, could be.....
public static bool NullableValueTryParse(string text, out int? nInt)
{
int value;
if (int.TryParse(text, out value))
{
nInt = value;
return true;
}
else
{
nInt = null;
return false;
}
}
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?)
This is the one liner you're looking fo:
DateTime? d = DateTime.TryParse("some date text", out DateTime dt) ? dt : null;
If you want to make it a proper TryParse pseudo-extension method, you can do this:
public static bool TryParse(string text, out DateTime? dt)
{
if (DateTime.TryParse(text, out DateTime date))
{
dt = date;
return true;
}
else
{
dt = null;
return false;
}
}
Here is a slightly concised edition of what Jason suggested:
DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;