Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq2Sql: Does HasValue and != null, work the same for nullable types?

Tags:

c#

linq-to-sql

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?

like image 301
Svish Avatar asked Mar 09 '09 10:03

Svish


1 Answers

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);
}
like image 71
Andrew Hare Avatar answered Oct 25 '22 07:10

Andrew Hare