Which way is preferred in expressions like this:
int? Id
{
get
{
int i;
return Int32.TryParse(Request["id"], out i) ? i : (int?)null;
}
}
is it better to cast on null
or create a new Nullable<T>
?
Which way is preferred in expressions like this:
int? Id
{
get
{
int i;
return Int32.TryParse(Request["id"], out i) ? i : (int?)null;
}
}
is it better to cast on null
or create a new Nullable<T>
?
I tend to prefer the (int?)
notation to Nullable<int>
. The language provides this syntactical sugar, so I try to use it.
This is also why I call it int
instead of Int32
.
The interesting thing is that you only have to define one of the return types. In other words, this will also work:
return Int32.TryParse(Request["id"], out i) ? (int?)i : null;
...even though the compiler suggests you have to cast the null: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '< null >'
The best is default(int?)
because it always works as expected (reference types, value types, and even in generics).
Do whatever is clearest for you.
That said I prefer to just return null
and the compiler work out the details.
It doesn't matter, it generates the exact same code. (int?)null
gets translated by the C# compiler to new Nullable<int>()
. You can see this for yourself by writing a small test program and looking at it with ildasm.exe
So "better" is merely what style you prefer. Consistent use of int? would be my personal preference.
One practical note: in a typical debug session you might well be interested in finding out that null is getting returned. Especially since the data you read doesn't produce what you expect. That becomes very easy if you write the null-returning statement on a separate line:
int i;
if (Int32.TryParse(Request["id"], out i)) return i;
else return null; // <== set breakpoint here.
Get's rid of the cast too. And produces the exact same code