0

I'm doing a school project and I'm struggling to sort my "Fruit" array. The values are all inputted from the user and that's all fine but every time I try and use Array.Sort I get this error:

NulllReferenceException was unhandled...

Can you help me sort my array with minimal coding?

Dim fruit_value As String = Fruit_Box.Text
Fruit(Fruit_counter) = fruit_value
Fruit_counter += 1
MessageBox.Show("Data has been entered")

For i = 0 To Fruit_counter - 1
    ' Array.Sort(Fruit) doesn't work here due to error coming from code below:
    Fruit_contents = Fruit_contents & (Fruit(i)).ToString & " | "
Next
MessageBox.Show(Fruit_contents)
djv
  • 15,168
  • 7
  • 48
  • 72
  • That seems to suggest that you actually have a variable named `Array` rather than using the `System.Array` class. If you set a breakpoint on that line (if you don't know how to debug with breakpoints, learn now) and mouse over `Array`, what does Intellisense tell you? – jmcilhinney Mar 15 '19 at 08:59
  • Hang on a minute. Your comment says that the error is coming from the code below rather than from the actual `Array.Sort` call. If that's the case, look at each reference on that line when the exception is thrown and see which reference is null, i.e. `Nothing`. There aren't many options. – jmcilhinney Mar 15 '19 at 09:39
  • I'm guessing that what is happening is that, when you sort the array, all the empty elements are being placed first, which means that `Fruit(I)` will be `Nothing` in many cases. In that case, you need to use the overload of `Array.Sort` that let's you specify only part of the array. – jmcilhinney Mar 15 '19 at 09:42
  • Yeah no worries thanks heaps for the feedbacks jmcilhinney!!! Yeah the error isn’t actually coming from array.sort but always the code below it so I’ll check out each reference in it and see what happens! – user11207307 Mar 15 '19 at 10:15
  • 1
    Don't bother. It will be as I said, i.e. sorting moves all the null references to the beginning of the array so `Fruit(0)` will always be `Nothing`, so calling `ToString` on it will always throw an exception. Do as I said. Read the documentation for the `Array.Sort` method or just pay attention to Intellisense when you type the code and you'll see what overloads are available. You need to call one that allows you to specify that only the portion of the array that you have populated should be sorted. – jmcilhinney Mar 15 '19 at 10:28

0 Answers0