Nate Koppenhaver
Nate Koppenhaver

Reputation: 1702

Unexplainable Null Reference Exception in VB.NET

I have an application for working with files. It needs to work with the files one character at a time. I am using an ArrayList to store the data. Here's the code that's causing the problem:

Dim fileData As ArrayList = Nothing  
Dim temp As Char = Nothing  
While Not EOF(open_file_number)  
    Input(open_file_number, temp)  
    fileData.Add(temp)  
End While  

The line of code that is throwing the Null Reference Exception is where I (attempt to) assign the value of temp to a new element in the fileData ArrayList. Anybody have an idea of what's going on here? Thanks

Upvotes: 0

Views: 1558

Answers (2)

Cheaney
Cheaney

Reputation: 1

What you need to do is change the following line:

Dim temp As Char = Nothing  

To:

Dim temp as Char = ''

There is a difference. I have experienced the same thing with String variables and have gotten the same issue.

Dim s as String = nothing

results in a NULL pointer when attempting to assign a value to 's'.

Dim s as string = String.empty

Does not.

Upvotes: 0

mellamokb
mellamokb

Reputation: 56779

Well, fileData is set to Nothing, so of course it will fire a NullReferenceException when you call .Add on it. Try setting it to a new instance:

Dim fileData As New ArrayList

Upvotes: 1

Related Questions