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>
?
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.
The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .
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.
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.
The best is default(int?)
because it always works as expected (reference types, value types, and even in generics).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With