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

2019-01-14 15:19发布

int n == 0;

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

Is it true that the result of expression (n == null) is always false since
a   value of type int  is never equal to   null of type int? (see warning below)

Warning CS0472 The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'

标签: c# null
8条回答
Emotional °昔
2楼-- · 2019-01-14 15:25

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.

查看更多
Anthone
3楼-- · 2019-01-14 15:33

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.*/
查看更多
倾城 Initia
4楼-- · 2019-01-14 15:40

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.

查看更多
仙女界的扛把子
5楼-- · 2019-01-14 15:42

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-14 15:43

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.

查看更多
成全新的幸福
7楼-- · 2019-01-14 15:43
 public static int? n { get; set; } = null;

OR

 public static Nullable<int> n { get; set; }

or

 public static int? n = null;

or

 public static int? n

or just

 public static int? n { get; set; } 


    static void Main(string[] args)
    {


    Console.WriteLine(n == null);

     //you also can check using 
     Console.WriteLine(n.HasValue);

        Console.ReadKey();
    }

The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null

查看更多
登录 后发表回答