Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable<int> vs. int? - Is there any difference?

Tags:

c#

.net

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 
like image 878
Zachary Scott Avatar asked Oct 26 '10 23:10

Zachary Scott


People also ask

Can int be Nullable?

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.

Can we compare int with null?

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.

What is the difference between int and int?

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.

Is Nullable int a value type?

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.


1 Answers

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.

like image 91
LukeH Avatar answered Sep 27 '22 21:09

LukeH