Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is preferred: new Nullable<int> or (int?)null?

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

like image 298
abatishchev Avatar asked Apr 29 '10 17:04

abatishchev


People also ask

What is the difference between nullable int and int?

No difference. int? is just shorthand for Nullable<int> , which itself is shorthand for Nullable<Int32> . Compiled code will be exactly the same whichever one you choose to use.

What is default of nullable int?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

Which is correct declaration of nullable integer?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Can int be nullable?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.


1 Answers

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

like image 82
Sam Harwell Avatar answered Oct 27 '22 00:10

Sam Harwell