DataTable cannot equal DBNull

I've seen this a couple of times in code, so it's worth mentioning.  There seems to be some confusion around what DBNull is supposed to be used for.  DBNull is meant to test field values of a DataTable for a value of NULL.  If you're doing something like

If DBNull(myDataTable) = False Then
 ' do something with the DataTable
End If

Then you're setting yourself up for a possible exception. DBNull on anything other than a proper DataTable field will always return false.

Consider the following test

Imports System.Data
Imports NUnit.Framework
<TestFixture()> _
Public Class DBNullTest
    <Test()> _
    Public Sub CanDataTableBeIsDBNull()
        Dim dt As DataTable = Nothing
        Assert.IsTrue(IsDBNull(dt))
    End Sub
End Class

CanDataTableBeIsDBNull will fail because dt is a DataTable type and not a field value from the DataTable.  So if you have to check to see if a DataTable is a valid object after an operation to populate the DataTable, use a comparison with Nothing instead:

    <Test()> _
    Public Sub CanDataTableBeNothing()
        Dim dt As DataTable = Nothing
        Assert.IsTrue(IsNothing(dt))
    End Sub

Posted by: Jeff
Posted on: 1/17/2010 at 1:37 AM
Categories: VB.NET
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed