Here's my starting point: a SortedDictionary with a custom Comparer:
Dim dict As SortedDictionary(Of Long, Object) = New SortedDictionary(Of Long, Object)(New CustomComparer())
To implement additional functionality, I need to extend my dictionary so I now have this:
Public Class CustomDict
Inherits SortedDictionary(Of Long, Object)
End Class
Dim dict As CustomDict = New CustomDict
Everything is fine up to this point. Now I just need to add my custom comparer:
Dim dict As CustomDict = New CustomDict()(New CustomComparer())
But the compiler thinks I am trying to create a two dimensional array.
The upshot is that if I use a class that extends SortedDictionary, I get compiler errors when using a custom comparer because it thinks I am trying to create an array. What I expect is that it would recognize the code as instantiating the class that inherits SortedDictionary, and for it to use the custom comparer.
To summarize, this compiles:
Dim dict As SortedDictionary(Of Long, Object) = New SortedDictionary(Of Long, Object)(New CustomComparer())
while this produces compiler errors related to two-dimensional arrays:
Public Class CustomDict
Inherits SortedDictionary(Of Long, Object)
End Class
Dim dict As CustomDict = New CustomDict()(New CustomComparer())
Is my syntax wrong? Or is there a Visual Studio setting (2017 Professional) to clarify to the compiler what my intention is? Any assistance would be appreciated.
When inheriting a class pretty much everything but its constructors are inherited. Therefore you must create the constructor on your own and make it call the constructor of the base class:
Public Class CustomDict
Inherits SortedDictionary(Of Long, Object)
'Default constructor.
Public Sub New()
MyBase.New() 'Call base constructor.
End Sub
Public Sub New(ByVal Comparer As IComparer(Of Long))
MyBase.New(Comparer) 'Call base constructor.
End Sub
End Class
Alternatively, if you always want to use the same comparer for your custom dictionary you can skip the second constructor and instead make the default constructor specify which comparer to use:
Public Sub New()
MyBase.New(New CustomComparer())
End Sub