0

I'm getting a syntax error when attempting to compile this code, and I'm not quite sure why. Could anyone help me with fixing this code?

DateTime? ModifiedDate = null; ModifiedDate = (dbReader["ModifiedDate"] == DBNull.Value ? null : DateTime.Parse(dbReader['ModifiedDate'].ToString())); 
2
  • 2
    What is the syntax error? I think I could figure it out, but it's better if you post it. Commented May 31, 2013 at 19:20
  • Note that there is no "if" statement involved. If you used an if/else to perform the assignments, the compiler would not have complained. Note also that this is a common question. See: stackoverflow.com/questions/202271/… Commented May 31, 2013 at 19:27

2 Answers 2

8

When it comes to the conditional operator, both sides of the condition should return the same type (or types that are implicitly convertible to each other).

Now null is not a specific type, which is part of the problem - you need to cast it to DateTime? so it will match the other side - which has another issue: you are using ' instead of ".

The following will work:

DateTime? ModifiedDate = dbReader["ModifiedDate"] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dbReader["ModifiedDate"].ToString()); 
Sign up to request clarification or add additional context in comments.

3 Comments

FWIW - you could also cast the DateTime.Parse half to (DateTime?) and get the same result.
@MarkBrackett - true, though I like the cast of null better for explicitness and readability (I think it is less surprising than a cast of DateTime to DateTime?).
The ' was a typo when I created this posting cuz of seperate network. I will give this a try. A customer just called w/ a problem so i gonna run off for an hour.
1
DateTime? ModifiedDate = dbReader["ModifiedDate"] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dbReader["ModifiedDate"].ToString()); 

You accidentally used the character separator instead of the string separator. It's fixed above.

5 Comments

No, it isn't. Still will not compile.
So there's something else... I'll see.
@Oded I'm not quite sure where...
Something additional.
Oh right, saw your answer now. +1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.