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()));
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
fletchsod
  • 3,560
  • 7
  • 39
  • 65
  • 2
    What **is** the syntax error? I think I could figure it out, but it's better if you post it. – It'sNotALie. May 31 '13 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: http://stackoverflow.com/questions/202271/why-is-this-code-invalid-in-c?answertab=active#tab-top – Anthony Pegram May 31 '13 at 19:27

2 Answers2

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());
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • FWIW - you could also cast the DateTime.Parse half to (DateTime?) and get the same result. – Mark Brackett May 31 '13 at 19:25
  • @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?`). – Oded May 31 '13 at 19:28
  • 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. – fletchsod May 31 '13 at 19:29
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.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103