Apparently Nullable<int>
and int?
are equivalent in value. Are there any reasons to choose one over the other?
Nullable<int> a = null; int? b = null; a == b; // this is true
As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables.
Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given. The compiler also optimizes this away because it is always false. It won't even load the x variable at all.
A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object. int helps in storing integer value into memory. Integer helps in converting int into object and to convert an object into int as per requirement.
Nullable types are neither value types nor reference types. They are more like value types, but have a few properties of reference types. Naturally, nullable types may be set to null . Furthermore, a nullable type cannot satisfy a generic struct constraint.
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.
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