none
Inheriting SortedSet(of T) with non default comparator. RRS feed

  • Question

  • Is it a possible to define a Class that inherits from SortedSet(of T) but does not use the default Comparer of class T  ?  For example, if I define the following class it will behave like a set of integers ordered from the smallest to the largest


    Class MyScores
    
    Inherits SortedSet(of Integer)
    
    …
    
    End Class
    But what if I want to reverse the order? I know I can create an instance of an ordered set with a non-default comparator with the constructor SortedSet(Of T)(IComparer(Of T)) and I could  encapsulate such object  in a new class and then recreate  all the interfaces. It would be simpler to use inheritance. but the following doesn't seem legit.


    Class MyScores
    
    Inherits SortedSet(of Integer)(new CustomComparator)
    
    …
    
    End Class

    I also tried shadowing the Comparer property but it also does not work. 






    • Edited by Ybaca Saturday, December 31, 2016 7:02 PM
    Saturday, December 31, 2016 6:46 PM

Answers

  • Try this:

    Class MyComparer
        Implements IComparer(Of Integer)
    
        Public Function Compare(x As Integer, y As Integer) As Integer Implements IComparer(Of Integer).Compare
            Return y - x
        End Function
    
    End Class
    
    
    Class MyScores
        Inherits SortedSet(Of Integer)
    
        Sub New()
            MyBase.New(New MyComparer)
        End Sub
    
    End Class
    

    • Marked as answer by Ybaca Sunday, January 1, 2017 4:13 PM
    Saturday, December 31, 2016 11:27 PM

All replies

  • Try this:

    Class MyComparer
        Implements IComparer(Of Integer)
    
        Public Function Compare(x As Integer, y As Integer) As Integer Implements IComparer(Of Integer).Compare
            Return y - x
        End Function
    
    End Class
    
    
    Class MyScores
        Inherits SortedSet(Of Integer)
    
        Sub New()
            MyBase.New(New MyComparer)
        End Sub
    
    End Class
    

    • Marked as answer by Ybaca Sunday, January 1, 2017 4:13 PM
    Saturday, December 31, 2016 11:27 PM
  • Perfect - thank you very much and Happy 2017
    Sunday, January 1, 2017 4:14 PM