Frosty555
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?
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.