Why type “int” is never equal to 'null'?

前端 未结 8 1373
迷失自我
迷失自我 2020-12-05 22:50
int n == 0;

if (n == null)    
{  
    Console.WriteLine(\"......\");  
}

Is it true that the result of expression (n == null) is alw

相关标签:
8条回答
  • 2020-12-05 23:08

    If you want your integer variable to allow null values, declare it to be a nullable type:

    int? n = 0;
    

    Note the ? after int, which means that type can have the value null. Nullable types were introduced with v2.0 of the .NET Framework.

    0 讨论(0)
  • 2020-12-05 23:10

    The usage of NULL applies to Pointers and References in general. A value 0 assigned to an integer is not null. However if you can assign a pointer to the integer and assign it to NULL, the statement is valid.

    To sum up =>

     /*Use the keyword 'null' while assigning it to pointers and references. Use 0 for integers.*/
    
    0 讨论(0)
  • 2020-12-05 23:11

    In C# using an uninitialized variable is not allowed.

    So

    int i;
    Console.Writeline(i);
    

    Results in a compilation error.

    You can initialize int with new such as:

    int anInt = new int();
    

    This will result in the Default value for int which is 0. In cases where you do wish to have a generic int one can make the int nullable with the syntax

    int? nullableInt = null;
    
    0 讨论(0)
  • 2020-12-05 23:12

    Very simply put, an int is a very basic item. It's small and simple so that it can be handled quickly. It's handled as the value directly, not along the object/pointer model. As such, there's no legal "NULL" value for it to have. It simply contains what it contains. 0 means a 0. Unlike a pointer, where it being 0 would be NULL. An object storing a 0 would have a non-zero pointer still.

    If you get the chance, take the time to do some old-school C or assembly work, it'll become much clearer.

    0 讨论(0)
  • 2020-12-05 23:12

    No, because int is a value type. int is a Value type like Date, double, etc. So there is no way to assigned a null value.

    0 讨论(0)
  • 2020-12-05 23:28

    Because int is a value type rather than a reference type. The C# Language Specification doesn't allow an int to contain null. Try compiling this statement:

    int x = null ;
    

    and see what you get.

    You get the compiler warning because it's a pointless test and the compiler knows it.

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