How can I write
string date = "12/2/2011";
DateTime? dt = date ?? DateTime.Parse(date);
this throws a compile time error. I know I can do tryparse or do if {}. Is there any way to do this in one line?
Try using the conditional operator ?: instead of the null-coalescing operator ??:
DateTime? dt = date == null ? (DateTime?)null : DateTime.Parse(date);
You also need to cast the null to DateTime? otherwise you will get a compile error.
This solution not only assigns null to the nullable DateTime dt when the string date is null or an empty string, but also when it contains an invalid date representation:
string date = null; // or "01/02/2011"
DateTime? dt;
DateTime temp;
if (DateTime.TryParse(date, out temp)) {
dt = temp;
} else {
dt = null;
}
The if-else statement can be replaced by a one line ternary expression, however not the declaration of temp:
DateTime temp;
dt = DateTime.TryParse(date, out temp) ? temp : (DateTime?)null;
else statement, since dt is null from the start.dt is a member variable, but not if it is a local variable. From the example given in the question, I do not see, whether dt is defined in a class or in a method.
DateTime? dt = date ? DateTime.Parse(date) : null;