Link to home
Start Free TrialLog in
Avatar of Frosty555
Frosty555Flag for Canada

asked on

Using IComparable to compare two classes

Another (I think reasonably easy) vb.net class/interface question.

I have a class called "Credentials" which holds a username/password combo in a hashed form. I want to be able to compare it to another credentials object created by the user in order to determine if the user entered the right username/password combination. Attached in the snippet is the barebones of the class.

I'd like to compare them like this:

' Stored somewhere
Dim cred1 as new Credentials("john", "mypassword")

' Provided by user
Dim cred2 as new Credentials("john", "userenteredthewrongthing")

If cred1.CompareTo(cred2) Then
      msgbox("Correct!")
Else
      msgbox("Access denied!")
End If

Now I know I could just go MAKE the CompareTo() method, have it take a credential object and presto - but wouldn't it be more correct to have the class implement the IComparable interface? So I did that. Again, see my code snippet.

But CompareTo() takes an object, not a Credentials class. How do I implement the comparison?
Public Class Credentials
    Implements IComparable
 
    Public usernamehash as String
    Public passwordhash as String
 
    Sub New()
        Throw New NotImplementedException()
    End Sub
    Sub New(ByVal user as String, ByVal pass as String)
        Throw New NotImplementedException()
    End Sub
 
    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
    End Function
End Class

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Jason Evans
Jason Evans
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Frosty555

ASKER

Ahh that's what you're supposed to do. I didn't know about DirectCast. Thank you!

I think actually IComparable might not quite be what I'm supposed to use since it is supposed to determine if the value is less than or greater than for the purposes of sorting... but nevertheless I see how you do this now.