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

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?

This question is related to c# nullable

The answer is


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

Similarly I did for long:

myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;

Another option is to use

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

I like this one most.


What Harry S says is exactly right, but

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

would also do the trick. (We Resharper users can always spot each other in crowds...)


What Harry S says is exactly right, but

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

would also do the trick. (We Resharper users can always spot each other in crowds...)


Another option is to use

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

I like this one most.


Similarly I did for long:

myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;

What Harry S says is exactly right, but

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

would also do the trick. (We Resharper users can always spot each other in crowds...)