C# code won't compile. No implicit conversion between null and int

48.5k views Asked by At

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.

2

There are 2 answers

2
Mehrdad Afshari On BEST ANSWER
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
0
AudioBubble On

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);