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

C#StringNullNullable

C# Problem Overview


> Possible Duplicate:
> https://stackoverflow.com/questions/858080/nullable-types-and-the-ternary-operator-why-wont-this-work

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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHcabnettekView Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#user26901View Answer on Stackoverflow