I’m trying to create a Quicksort base class using VB.NET, taking it an array of IComparable elements. The signature looks like this:
public shared sub Sort(ByVal values() as IComparable)
However, when I pass in an array of doubles, the compiler is giving me errors.
Dim numbers(100) as double Dim random as new Random(0) for i as integer = 0 to numbers.length - 1 numbers(i) = random.NextDouble() Next QuickSort.Sort(numbers) ' gives compiler error.
The error is:
Error 88 Value of type '1-dimensional array of Double' cannot be converted to '1-dimensional array of System.IComparable' because 'Double' is not derived from 'System.IComparable'. C:\Proving Grounds\Module1.vb
The .NET documentation states that double’s implement IComparable. Why isn’t the .NET compiler letting me do this?
Although
doublecan be cast toIComparable, it doesn’t mean thatdouble[]can be cast toIComparable[]. A simple option would be to create a newIComparable[]array and copy the data over – or in your case, simply start the original array asIComparable[].Actually, I’d be tempted to use the generic
IComparable<T>orIComparer<T>interfaces, or theComparison<T>delegate – all using generics – this also allows use ofComparer<T>.Defaultand non-default comparers.