c# why can't a nullable int be assigned null as a value

mancmanomyst picture mancmanomyst · Dec 1, 2008 · Viewed 125.3k times · Source

Explain why a nullable int can't be assigned the value of null e.g

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));

What's wrong with that code?

Answer

Harry Steinhilber picture Harry Steinhilber · Dec 1, 2008

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));