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

前端 未结 8 1374
迷失自我
迷失自我 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:28

    "Value types" in .NET (like int, double, and bool) cannot, by definition, be null - they always have an actual value assigned. Check out this good intro to value types vs. reference types.

    0 讨论(0)
  • 2020-12-05 23:30
     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

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