Groups | Blog | Home
all groups > vb.net upgrade > december 2003 >

vb.net upgrade : cast as operator


Robert Edwards
12/4/2003 12:43:40 PM
Is it possible to take a string of "<>" or ">=" and cast those as
comparison operators?

My function is receiving these as a string and it would avoid me having
to do:

Select Case
Case "<>"

Case "<="


Does this make sense?

Bobby


*** Sent via Developersdex http://www.developersdex.com ***
Jay B. Harlow [MVP - Outlook]
12/4/2003 4:33:21 PM
Robert,
[quoted text, click to view]
Have you considered using a Delegate instead of a string?

Public Delegate Function CompareFunction(ByVal lhs As String, ByVal rhs
As String) As Boolean

Public Sub DoSomething(ByVal arg1 As String, ByVal arg2 As String, ByVal
compare As CompareFunction)
If compare(arg1, arg2) Then
' the comarison was true!
End If
End Sub

Private Function CompareLess(ByVal lhs As String, ByVal rhs As String)
As Boolean
Return lhs < rhs
End Function

Private Function CompareGreater(ByVal lhs As String, ByVal rhs As
String) As Boolean
Return lhs > rhs
End Function

Private Function CompareNotEqual(ByVal lhs As String, ByVal rhs As
String) As Boolean
Return lhs <> rhs
End Function

Private Function CompareGreaterEqual(ByVal lhs As String, ByVal rhs As
String) As Boolean
Return lhs >= rhs
End Function

Public Sub Main()
DoSomething("a", "b", AddressOf CompareGreater)
DoSomething("a", "b", AddressOf CompareLess)
End Sub

Of course you may still need a select case someplace else depending on where
you are getting the "operator" from. Also if you are comparing more then
just strings, that will complicate things. I would consider basing the above
on IComparable instead of a specific type, allowing the routine to be used
in wider cases.

Public Delegate Function CompareFunction(ByVal lhs As IComparable ,
ByVal rhs As IComparable) As Boolean

Public Sub DoSomething(ByVal arg1 As String, ByVal arg2 As String, ByVal
compare As CompareFunction)
If compare(arg1, arg2) Then
' the comparison was true!
End If
End Sub

Private Function CompareLess(ByVal lhs As IComparable, ByVal rhs As
IComparable) As Boolean
Return lhs.CompareTo(rhs) < 0
End Function

Private Function CompareGreater(ByVal lhs As String, ByVal rhs As
String) As Boolean
Return lhs.CompareTo(rhs) > 0
End Function

Of course using IComparable will cause value types (Integer) to be boxed
when you call the function.

Hope this helps
Jay

[quoted text, click to view]

hirf-spam-me-here NO[at]SPAM gmx.at
12/4/2003 10:52:15 PM
* Robert Edwards <redwards@csa.co.orange.ca.us> scripsit:
[quoted text, click to view]

No.

--
Herfried K. Wagner [MVP]
AddThis Social Bookmark Button