tags:

views:

331

answers:

1

Is there any reason why I should choose one of these over the other? Or doesn't it really matter?

var a = data.Cars.Where(ø => ø.LicensePlate != null);

var b = data.Cars.Where(ø => ø.LicensePlate.HasValue);

I have used != null before, but starting to think I should maybe switch, since HasValue kind of reads better. What do you guys think? Is there any difference at all? Other than one character extra? Any performance differences? Sql differences?

+6  A: 

No, both statements are the same and you ought to choose whichever one you find more readable.

Something interesting to note is that the compiler will replace null comparisons on a Nullable<T> with a call to HasValue. In other words this:

class Program
{
    static void Main()
    {
     int? i = 0;

     Console.WriteLine(i != null);
     Console.WriteLine(i.HasValue);
    }
}

gets compiled to this:

private static void Main()
{
    int? i = 0;
    Console.WriteLine(i.HasValue);
    Console.WriteLine(i.HasValue);
}
Andrew Hare
nice! how do you see the result of a compilation like that?
Svish
I used Reflector to analyze the assembly - http://www.red-gate.com/products/reflector/
Andrew Hare