What's the difference between 'int?' and 'int' in C#?

C#SyntaxTypesNullable

C# Problem Overview


I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.

It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it? My stackoverflow search-fu is apparently too low....

C# Solutions


Solution 1 - C#

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

Solution 2 - C#

Solution 3 - C#

int? is the same thing as Nullable. It allows you to have "null" values in your int.

Solution 4 - C#

int belongs to System.ValueType and cannot have null as a value. When dealing with databases or other types where the elements can have a null value, it might be useful to check if the element is null. That is when int? comes into play. int? is a nullable type which can have values ranging from -2147483648 to 2147483648 and null.

Reference: https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Solution 5 - C#

Int cannot accept null but if developer are using int? then you store null in int like int i = null; // not accept int? i = null; // its working mostly use for pagination in MVC Pagelist

Solution 6 - C#

the symbol ? after the int means that it can be nullable.

The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.

Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.

Solution 7 - C#

you can use it when you expect a null value in your integer especially when you use CASTING ex:

x= (int)y;

if y = null then you will have an error. you have to use:

x = (int?)y;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoriView Question on Stackoverflow
Solution 1 - C#Forgotten SemicolonView Answer on Stackoverflow
Solution 2 - C#KyleLanserView Answer on Stackoverflow
Solution 3 - C#Charles GrahamView Answer on Stackoverflow
Solution 4 - C#Krishnaveni BView Answer on Stackoverflow
Solution 5 - C#Fahad Jamal uddinView Answer on Stackoverflow
Solution 6 - C#sanmatrixView Answer on Stackoverflow
Solution 7 - C#Taher AssadView Answer on Stackoverflow