Checking a nullable for null



now that you have defined a variable which might be null, checking whether that is the case is obviously important. You can do this in two ways: Just compare the variable to the null kewyord, like you would for any other types, or use the HasValue property which a nullable object inherits from the System.Nullable struct. Here''s an example:

int? nullable = null;  
if (nullable == null)  
    Console.WriteLine("It's a null!");  
if (!nullable.HasValue)  
    Console.WriteLine("It's a null!");

From the System.Nullable, a nullable object also inherits the Value property. This can be used to retrieve the actual value of the nullable object. However, for simple comparison operations, e.g. using the == and the != operators, C# lets you omit the Value property and just directly compare the nullable object. In other words, both of these examples accomplish the same thing:

int? nullable = 42;

if (nullable.Value == 42)  
    Console.WriteLine("It's 42!");  

if (nullable == 42)  
    Console.WriteLine("It's 42!");

0 Comment's

Comment Form

Submit Comment