views:

515

answers:

1

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?

+3  A: 

Although double can be cast to IComparable, it doesn't mean that double[] can be cast to IComparable[]. A simple option would be to create a new IComparable[] array and copy the data over - or in your case, simply start the original array as IComparable[].

Actually, I'd be tempted to use the generic IComparable<T> or IComparer<T> interfaces, or the Comparison<T> delegate - all using generics - this also allows use of Comparer<T>.Default and non-default comparers.

Marc Gravell
Oh, right. I should actually USE those new language features.
David Sokol