EDIT: I hadn't read the question carefully enough; the problem isn't that the conditional operator doesn't like nulls - it's that it needs to know what the overall type of the expression should be... and that type has to be the type of either the left-hand side, or the right-hand side. null
itself is a type-less expression which can be converted to many types; int
is a perfectly valid type, but it's one of the types which null
can't be converted to. You can either make the right-hand side explicitly of type int?
and get the implicit conversion of int
to int?
from the left-hand side, or you can perform a cast on the left-hand side, and get the implicit conversion of null
to int?
.
My answer is like James's, but casting the null instead:
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? rv : (int?) null;
}
}
This is to emphasize that it's not a null reference; it's a null value of type int?
. At that point, the conversion of the int rv
is obvious.
There are two other alternatives along the same lines to consider though:
return int.TryParse(userIdString, out rv) ? rv : new int?();
return int.TryParse(userIdString, out rv) ? rv : default(int?);
Personally I think the "casted null" is the nicest form, but you can make up your own mind.
Another alternative would be to have a generic static method:
public static class Null
{
public static T? For<T>() where T : struct
{
return default(T?);
}
}
and write:
return int.TryParse(userIdString, out rv) ? rv : Null.For<int>();
I don't think I really like that, but I offer it for your inspection :)