"Is" gets a new role in VB 2008

Thanks to Julie’s post, I decided to dig deeper into the depths of VB than any sane man should go. While playing with nullable dates in the query, I was wondering why I could get the number of orders with a null ShipDate.


I tried:


Dim query = From order In db.SalesOrderHeaders _
            Where Not order.ShipDate = Nothing

 


that returned 0.


Then I thought what about Is ?


Dim query = From order In db.SalesOrderHeaders _
            Where Not order.ShipDate Is Nothing

That returns the correct number, which in my modified data is 2.

Now the thing to note here is that ShipDate is a Nullable(of Date), and as such is a value type.  If you try to use the Is operator with a nullable type in VB 2005 you’ll get an error telling you can’t use Is with value types.  In fact you’ll get the same error in VB9 (2008) unless the operand is Nothing, e.g:

Dim dt1 As Date?

Dim dt2 As Date?

Dim result As Boolean = dt1 Is Nothing ‘ legal

Dim result2 As Boolean = dt1 Is dt2 ‘ ILLEGAL

So, the new role for Is is when comparing a nullable type to the Nothing constant.

 And likewise you can use IsNot with Nothing on nullable types too,

This entry was posted in 2087, 2088, 491, 5162. Bookmark the permalink.

2 Responses to "Is" gets a new role in VB 2008

  1. Julie says:

    “than any sane man should go”

    You said it first! :-)

  2. Aaron says:

    That makes sense from a SQL point of view. Null normally doesn’t equal null without setting an option. I guess they took the true meaning of null when they made nullable types.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>