Thanks to Jan, who gives me some remarks on my code, I have created a final update on the sort method.
Because in my comparer class both x and y are objects, I used automatic casting. VB.Net supports this VB6-behaviour when the option Strict is disabled (which is the default value). So by setting the Option Strict On, the code isn’t compiling anymore.
As you can see in the code below, we have rewritten the code of the PersonComparerName (Sorts on the name of persons).
Public Class PersonComparerName
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim xEntity As person
Dim yEntity As person
If GetType(person).IsInstanceOfType(x) Then
xEntity = CType(x, person)
Else
Throw New ApplicationException("Casting problem...")
End If
If GetType(person).IsInstanceOfType(x) Then
yEntity = CType(y, person)
Else
Throw New ApplicationException("Casting problem...")
End If
If xEntity.Name = yEntity.Name Then
Return 0
ElseIf xEntity.Name < yEntity.Name Then
Return -1
Else
Return 1
End If
End Function
End Class
We haven’t add here the PersonComparerCityName class, but the change is identical. The dimensioning of xEntity and yEntity is still the same, except that we don’t give directly the correct value. But we first check that the types matches. If not, then we throw an exception, else we set our variables to the correct value and we use DirectCast to do this.
In our form we have a try/catch block, which shows a messagebox when there’s an exception.
For the rest the code stays the same.
Also, I have to create a Comparer for each class I want to sort. Jan mentioned me to you can also use Reflection, so we have a dynamic sorting. Later I will look for this solution.