90

Possible Duplicate:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?

Why doesn't this work? Seems like valid code.

  string cert = ddCovCert.SelectedValue;
  int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
  Display(x);

How should I code this? The method takes a Nullable. If the drop down has a string selected I need to parse that into an int otherwise I want to pass null to the method.

3

2 Answers 2

290
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
2
  • 4
    so weird that you need to cast null.. why couldn't null be a universal type?
    – sksallaj
    Commented Feb 26, 2016 at 19:50
  • 1
    this is also possible: int? x = string.IsNullOrEmpty(cert) ? null : (int?)int.Parse(cert);
    – Menahem
    Commented May 17, 2016 at 14:20
10

I've come across the same thing ... I usually just cast the null to (int?)

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);

Not the answer you're looking for? Browse other questions tagged or ask your own question.