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

后端 未结 7 1157
甜味超标
甜味超标 2020-12-02 17:44

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 pre

相关标签:
7条回答
  • 2020-12-02 18:24

    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

    0 讨论(0)
  • 2020-12-02 18:27

    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;
    
    0 讨论(0)
  • 2020-12-02 18:29

    int? is Nullable.

    MSDN: Using Nullable Types (C# Programming Guide)

    0 讨论(0)
  • 2020-12-02 18:34

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

    0 讨论(0)
  • 2020-12-02 18:37

    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

    0 讨论(0)
  • 2020-12-02 18:38

    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.

    0 讨论(0)
提交回复
热议问题