I did create a XDateTime class that is able to handle inaccurate date and time.
This class has all the CType operators required to convert to and from a string and it has been fully tested during the last months.
Public Shared Widening Operator CType(ByVal xDateTime As FrameworkBL.XDateTime) As String
Dim retrunValue As String = Nothing
If xDateTime Is Nothing Then
retrunValue = Nothing
Else
retrunValue = xDateTime.StringValue
End If
Return retrunValue
End Operator
Public Shared Narrowing Operator CType(ByVal value As String) As FrameworkBL.XDateTime
Dim returnValue As FrameworkBL.XDateTime = Nothing
If String.IsNullOrEmpty(value) Then
returnValue = Nothing
Else
returnValue = New FrameworkBL.XDateTime(value)
End If
Return returnValue
End Operator
However, when a ByRef object parameter return a string, my CType operators seems to be ignored and a cast Exception is raised.
Private Sub Test()
Dim myXDateTime As FrameworkBL.XDateTime
myXDateTime = "200101010000007" 'Ok
Me.Temp1(myXDateTime) 'Ok
Me.Temp2(myXDateTime) 'Ok
Me.Temp3(myXDateTime) 'Unable to cast object of type 'System.String' to type 'FrameworkBL.XDateTime'
End Sub
Private Sub Temp1(ByRef myObject As String)
myObject = "200201010000007"
End Sub
Private Sub Temp2(ByRef myObject As XDateTime)
myObject = "200301010000007"
End Sub
Private Sub Temp3(ByRef myObject As Object)
myObject = "200401010000007"
End Sub
This kind of problem is documented by Microsoft but I couldn’t find a working solution to fix this problem. Am I in a dead end or is there an option that would allow me to keep my ByRef Object parameter??
The solution is not to write this code. In fact, your code shouldn’t even compile, and never mind the
ByRef. You simply cannot assign a string to anObject, and rightly so. You should enableOption Strict Onin your project settings.This is the correct and expected behaviour.
Apart from that, your operator implementations can (and should) be drastically shortened by taking advantage of the VB
Ifoperator. This makes the redundant initialisation and assignments go away:Same for the other way round. That said, I don’t think conversion operators should ever work on
Nothingvalues. This just makesNothingcreep into code where it shouldn’t.