1

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.

4
  • What is the definition of the variable Messages? Commented Sep 15, 2013 at 14:16
  • 1
    I'd also try to avoid using an ArrayList. Try using collections from the System.Collections.Generic namespace, eg List(Of T) ... Commented Sep 15, 2013 at 14:19
  • @Styxxy: ...List(Of String) in this case... Commented Sep 15, 2013 at 14:53
  • @Neolisk In this case, yes ;-). Commented Sep 15, 2013 at 15:33

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You get NullReferenceExceptions because Messages is in fact null.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.