Liam Smith
Liam Smith

Reputation: 11

NullReferenceException when adding to ArrayList

I am attempting to add to an ArrayList using the following.

Dim lines() As String = IO.File.ReadAllLines("C:\xTools\messages.txt")
For Each line As String In lines
  Dim parts As String() = line.Split(New String() {":"}, StringSplitOptions.None)
  Dim message As String = String.Join(" ", parts)
  If Not message = Nothing Then
    Messages.Add(message)
  End If
Next

All I get is NullReferenceExceptions on Messages.Add(message). Please advise.

Upvotes: 1

Views: 2218

Answers (2)

Victor Zakharov
Victor Zakharov

Reputation: 26434

Whenever you get NullReferenceException in a particular line, examine the line with respect to your code flow, i.e. you generally should know which of the variables or expressions can get a value of Nothing, so start with those first. Use either mouse hover or your immediate window.

In your example, message cannot be Nothing, because it's been checked previously for that. Also please do consider changing it to Is Nothing, rather than = Nothing. As written, it will also react to String.Empty, which is misleading. If you really want this behavior, use String.IsNullOrEmpty.

So the only thing that can be Nothing is Messages, which was probably never initialized:

Messages = New ArrayList

Or inline with declaration:

Dim Messages As New ArrayList

If you know that your Messages will always contain a list of strings, consider changing to Generic.List(Of String), you should get what you have now + type safety. You are only stuck with ArrayList class if using framework 1.1, and frankly by now all your projects should be at least 2.0, so consider upgrading if you haven't done so yet.

Upvotes: 2

olydis
olydis

Reputation: 3310

You get NullReferenceExceptions because Messages is in fact null.

Make sure that Messages is initialized with something, e.g. a new instance of ArrayList.

Upvotes: 0

Related Questions