I'm returning results from a stored procedure and passing them off to a function for further processing. In some cases, it's possible (and perfectly fine) for one of the fields, a date value, to return null.
However, whenever I pass the null into the function, an exception is thrown trying to convert the null into there function parameter's type. What is the best way to handle this?
Data:
Name StartDate EndDate
Bob 01/01/2013 NULL
Calling Function:
MyFunction(
DataRow.Item("StartDate"),
DataRow.Item("EndDate")) ' <--- invalid cast exception
Function:
Public Function MyFunction(
ByVal StartDate as Date,
ByVal EndDate as Date) As Object
....
Return something
End Function
EDIT: Lots of great tips but still no dice.
Declaring the DateTime type in the function as nullable, ByVal EndDate as DateTime?
, results in System.InvalidCastException: Specified cast is not valid.
Using DataRow.Field(Of DateTime)("EndDate") along with declaring the parameter as a nullable type results in System.InvalidCastException: Cannot cast DBNull.Value to type 'System.DateTime'
EDIT2: Found a source of one of my problems. I was using Iif(), and one of the values was of type System.DBNull, the other was of type Date. And both the true and false parts must be the same type. Took me a while to spot that.