Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type "int" is never equal to 'null'?

Tags:

c#

null

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?'

like image 340
avirk Avatar asked May 31 '11 17:05

avirk


People also ask

Can int type be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

What does int null mean?

Value types like int contain direct values rather than references like ReferenceType . A value cannot be null but a reference can be null which means it is pointing to nothing. A value cannot have nothing in it.

Is null or empty int?

Int is a value type so it cannot be null. Empty value of int depends on the logic of your application - it can be 0 or -1 or int. MinValue (well, technically, any number).

Is nullable int the same as int?

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.


1 Answers

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.

like image 50
D'Arcy Rittich Avatar answered Sep 21 '22 07:09

D'Arcy Rittich