8

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?

6
  • 1
    You have an extra question mark there. It should be DateTime? dt = date ? DateTime.Parse(date) : null; Commented Dec 1, 2011 at 20:14
  • sorry, just edited the question to date ?? DateTime.Parse(date) from date ?? null : DateTime.Parse(date) Commented Dec 1, 2011 at 20:15
  • 2
    Nope, C# supports the ?? operator (called elvis operator in Groovy). It returns the right side value only if the value is null, otherwise returns the value itself. Commented Dec 1, 2011 at 20:15
  • 1
    @EvertonAgner Interesting. In C# it's called "The Null Coalescing Operator". I like Elvis more. Commented Dec 1, 2011 at 20:19
  • You are having a compilation error because you are assigning a string to a DateTime. As the others described the ?? return the object if it is not null, which is the case in your code. Commented Dec 1, 2011 at 20:23

4 Answers 4

25

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.

Sign up to request clarification or add additional context in comments.

Comments

3
string date = "12/2/2011";

DateTime? dt = String.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);

Comments

2

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;

3 Comments

Downvoter please comment. What is wrong with my solution? It will not only detect when date is null, but also when it does not contain a valid date string. Note also that dt is nullable.
I just see no reason for your else statement, since dt is null from the start.
@EvertonAgner: Only if 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.
1
string date = "12/2/2011";
date = Convert.ToDateTime(date);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.