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?'
If you want your integer variable to allow null values, declare it to be a nullable type:
Note the
?
after int, which means that type can have the valuenull
. Nullable types were introduced with v2.0 of the .NET Framework.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 =>
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.
Because
int
is a value type rather than a reference type. The C# Language Specification doesn't allow anint
to contain null. Try compiling this statement:and see what you get.
You get the compiler warning because it's a pointless test and the compiler knows it.
No, because
int
is a value type.int
is aValue
type likeDate
,double
, etc. So there is no way to assigned anull
value.OR
or
or
or just
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