|
-
May 9th, 2007, 03:13 PM
#8
Thread Starter
Frenzied Member
Re: [RESOLVED] Compare objects
 Originally Posted by jmcilhinney
That MSDN link is for the IComparable.CompareTo method. I've been telling you to implement IComparable from the start. As I also said, you should be implementing the generic version of the interface in .NET 2.0. If you implement the standard IComparable interface then your code would look something like this:
vb Code:
Public Class Thing
Implements IComparable
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
If Not TypeOf obj Is Thing Then
Throw New ArgumentException("Object is not of type Thing.", "obj")
End If
Dim otherThing As Thing = DirectCast(obj, Thing)
'Compare Me with otherThing here.
End Function
End Class
Note that the object being compared to is passed via an Object reference, which means that you must check its type at run time and allow for it to be the wrong type. If you implement the generic version of the interface that is taken care of at compile time.
vb Code:
Public Class Thing
Implements IComparable(Of Thing)
Public Function CompareTo(ByVal other As Thing) As Integer Implements System.IComparable(Of Thing).CompareTo
'Compare Me with other here.
End Function
End Class
It's not possible to pass any object that is not type Thing so you don't have to test its type or cast and there's no possibility of an exception.
thanks for the code... i follow the example at the link and implemented the standard interface... i will change to a generic one, like you posted... thx
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|