If you do a small experiment, you would understand perfectly what is happening:
Dim normalDate As Date = Now
Dim nullableDate As Nullable(Of Date) = normalDate
Dim normalToText As String = normalDate.ToString("dd/MM/yy") 'Works perfectly
Dim nullableToText As String = nullableDate.ToString("dd/MM/yy") 'Error
The content in both variables, normalDate
and nullableDate
, is identical but they are not: the ToString("date in certain format")
functionality expects a Date
type as input; what you are sending is a modified version of the Date type (not too different, but not the same either). With CDate
what you are doing is converting the modified version of Date into an actually valid Date type and thus the ToString() functionality works without any problem.
Are you doing the right thing? Yes, as far as CDate can deal with "nulls" (CDate(Nothing)
does not output any error): you are adapting the given variable to what ToString() expects.
NOTE: I have checked the exact error output by the code above and it effectively delivers a "Conversion from string "dd/MM/yy" to type 'Integer' is not valid.". Thus the error you are getting is the standard error when intending to use ToString("date") with a Nullable Date; not too descriptive error, this is true.