views:

189

answers:

6

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> ?

+2  A: 

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.

Greg D
+1  A: 

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 >'

Nelson
+10  A: 

The best is default(int?) because it always works as expected (reference types, value types, and even in generics).

280Z28
Not seen this before, I like it! I've always used (int?)null and always felt it was clunky.
Daniel Renshaw
+1  A: 

Do whatever is clearest for you.

That said I prefer to just return null and the compiler work out the details.

C. Ross
A: 

What about

int? i;
Int32.TryParse(Request["id"], out i);
return i;
juharr
No, TryParse() only takes an int for the out variable.
Nelson
But that's probably because Nullable<> didn't exist before. No reason they couldn't implement it now.
Nelson
@Nelson duh, guess I should try my ideas out in VS first.
juharr
The only reason I found out is because I tried it, but it does make sense... :)
Nelson
+3  A: 

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

Hans Passant