Search code examples
asp.netvb.netasp.net-3.5strongly-typed-dataset

Problem with Inheritance and NullValue of a Strongly Typed DataSet


What is the simplest/cleanest/easiest/best way to handle Null value of a Strongly Typed DataSet in the following case :

  • A base class has a Nullable value that is set through it's constructor
  • The derived class's constructor has Strongly Typed DataSet Row as parameter and it Throw exception when accessing a null value.

Here a simplified example to demonstrate the problem I'm facing. Any resemblance to your code is purely coincidental.

Public MustInherit Class BaseClass
     Private _Number as Nullable(of integer)
     Public Sub New(Number as Nullable(of integer))
         _Number = Number 
     End Sub
End Class

Public Class DerivedClass
    Inherits BaseClass

    'Throw System.Data.StrongTypingException "The value for column 'Number'
    'in table 'SomeData' is DBNull." when Number is null
    Public Sub New(DataRow as my DataDLL.SomeDataRow)
          MyBase.New(DataRow.Number) 
    End Sub

    'First statement of this 'Sub New' must be a call to 'MyBase.New' 
    'or 'MyClass.New' because base class 'BaseClass' of 'DerivedClass' 
    'does not have an accessible 'Sub New' that can be called with no arguments
    Public Sub New(DataRow as my DataDLL.SomeDataRow)
         If TermRow.IsNumberNull() Then 
              MyBase.New(Nothing)
         Else
              MyBase.New(DataRow.Number )
         End If
    End Sub  

    'Also Throw System.Data.StrongTypingException because As part of preparing 
    'the argument list for the call to IIf, the Visual Basic compiler calls 
    'every function in every expression.  
    Public Sub New(DataRow As MyData)
        MyBase.New(DirectCast(IIf(DataRow.IsNumberNull(), _
                                  Nothing, _
                                  TermRow.Number), Nullable(Of Integer)))
    End Sub

End Class

I put 3 Public Sub New only to show 3 alternatives I considered.


Solution

  • That makes sense, you have to check for DBNull, which is not the same as Integer?

    Instead of IIF, Try the IF Operator, witch is new to .NET 3.5. You also have to cast Nothing to a Nullable(Of Integer) because the If function will return 0 otherwise; The return type of the return value is decided based on the wider of the types of the true-part and the false-part.

    Public Sub New(DataRow As MyData)
        MyBase.New(If(DataRow.IsNumberNull(), _
                      DirectCast(Nothing, Nullable(Of Integer)), _
                      DataRow.Number))
    End Sub