0

I keep getting window that pops up when I run a VB.NET console program I made that simply says "Object reference not set to an instance of an object." The window doesn't even say "error" or anything--the title is simply the name of the project. However...I'm assuming this is something I don't want.

I searched around a bit and found posts about similar messages but couldn't figure out how they applied to my situation.

Here is some of my code. (This program is supposed to take some data from a preformatted text file that describes the geometry of a cross section of a river and systematically enters some new geometric data to represent the riverbed being cleaned/cleared out in a certain way, and then write the new data to a new file in a similar format.)

Imports System
Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Module module1

    Public Sub Main()

        Using sr As New StreamReader("C:\inputfile.txt")

            Using outfile As New StreamWriter("C:\outputfile.txt")

                Dim line As String = ""
                Dim styles As Globalization.NumberStyles

                styles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint

                Dim stations(-1) As Double
                Dim elevations(-1) As Double
                Dim i As Integer = 0

                Do
                    Try
                        line = sr.ReadLine()

                        Dim stringarray() As String = line.Split()
                        ReDim Preserve stations(i)
                        ReDim Preserve elevations(i)
                        stations(i) = Double.Parse(stringarray(0), styles)
                        elevations(i) = Double.Parse(stringarray(1), styles)
                    Catch ex As Exception

                        MsgBox(ex.Message)

                    End Try
                    i = i + 1

                Loop Until line Is Nothing


                Dim min As Double = elevations(0)
               (some more code.....)

          End Using

        End Using

      End Sub

    End Module

I only included the first part of my code because when I put a break at the "Loop Until line Is Nothing" statement, the message didn't come up until after I went through the break, but when I put the break at the "Dim min As Double = elevations(0)" statement, the message came up before the program got to the break.

I don't really get what's wrong with my code. Anyone have any ideas?

Thanks!

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Brad Rock
  • 1
  • 1
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Steve Dec 03 '13 at 20:34
  • I see a number of people have answered it already. My two cents, in general that `Object Reference Not Set to an Instance of an Object` error refers to something that is null that is not supposed to be. You basically need to put in a breakpoint at the very first line, step through until you see what is throwing that and I am will to be its `null`. From everyones answers it looks like you created an array and never dim'd it to the right length. Imagine taking a penny and trying to put it in a jar with a lid and you never even specified how big the jar should be. – logixologist Dec 03 '13 at 20:49
  • To close in on the error, comment-out the `Try/Catch` (the error is obviously thrown within that, hence the message but no error message). When the code stops with an error, move the mouse cursor over `i` (is it 0 or higher?) and try if you can see which variable is actually causing the error. – KekuSemau Dec 03 '13 at 21:05

3 Answers3

0

The code fails after the last line has been read because the exit condition (Loop Until) doesn't know that you have reached the end of file. So another loop is started and the code tries to read an inexistent line. The last ReadLine returns Nothing, but the code tries to split it.

You could add a check before trying to split the line and jump directly to the Loop Until statement if you don't have anymore lines to read. Of course I also suggest to remove the array redim at every loop and use a more flexible List(Of Double)

Dim stations = New List(Of Double)
Dim elevations = New List(Of Double)

Do
    Try
        ' After the last line this command returns null (Nothing in VB)
        line = sr.ReadLine()

        if line IsNot Nothing Then
            Dim stringarray() As String = line.Split()
            stations.Add(Double.Parse(stringarray(0), styles))
            elevations.Add(Double.Parse(stringarray(1), styles))
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

Loop Until line Is Nothing
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    `ReDim Preserve stations(0)` creates a perfectly valid array with one element (at index 0). I don't see where the error actually is...? – KekuSemau Dec 03 '13 at 20:52
  • @KekuSemau right, I haven't used that statement for years and probably I have forgetten its inner workings. However please check the updated answer – Steve Dec 03 '13 at 21:21
0

See if this works any better:

Public Sub Main()

    Dim styles As Globalization.NumberStyles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
    Dim stations As New List(Of Double)
    Dim elevations As New List(Of Double)

    For Each line As String in File.ReadLines("C:\inputfile.txt")
        Try
            Dim stringarray() As String = line.Split()
            stations.Add(Double.Parse(stringarray(0), styles))
            elevations.Add(Double.Parse(stringarray(1), styles))

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Next Line

    Dim min As Double = elevations(0)

    Using outfile As New StreamWriter("C:\outputfile.txt")

    End Using
End Sub

Note that I moved your output file to the end... you haven't written anything yet, and so it's a good idea to wait as long as possible to open it, to keep it open for as short a time as possible.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

OK...I feel really dumb now...after reading through all of your answers and looking at Steve's code, I realized my code was going through the loop one last time where "line" was set as nothing at the beginning of the loop and it was still trying to add "nothing" as an element to the arrays. The key to fixing it was adding an "If line IsNot Nothing" statement before the statements adding elements to the arrays, which Steve had.

Thank you all for your answers!

Brad Rock
  • 1
  • 1