Home > Net >  Null Reference Exception on List of Strings
Null Reference Exception on List of Strings

Time:07-09

I've been looking at this thread as a way to create a "smart" method for concatenating strings. I have a set of properties where some of them might be null, in which case, I'd like to remove them from the filtered list before using the String.Join method. So, I have something like this:

Dim filteredList = (New List(Of String) From {
    a.ToString(),
    b.ToString(),
    c.ToString()
    }).Where(Function(x) Not String.IsNullOrWhiteSpace(x))
Dim result As String = String.Join(" | ", filteredList)

There are instances where a, b, and/or c could be null. When I run this code, I get a null reference exception saying one of the properties .get returned nothing and the code bails. Is there a way to fix this?

Edit

I guess I could fix this by checking if a, b, or c were null before adding them to the list like this:

Dim fullList = New List(Of String)
If a IsNot Nothing Then fullList.Add(a.ToString())
If b IsNot Nothing Then fullList.Add(b.ToString())
If c IsNot Nothing Then fullList.Add(c.ToString())

Dim filteredList = fullList.Where(Function(x) Not String.IsNullOrWhiteSpace(x))
Dim result As String = String.Join(" | ", filteredList)

Is this the best way to handle this situation? Or is there a more elegant way?

CodePudding user response:

Calling the ToString() method on a null object will result in a NullReferenceException.

Instead, you will need to:

  1. Filter to return just the values that are not null
  2. Select the value of ToString on the filtered set
  3. Then join

Also, there really is no need to convert the array to a List but I would convert the resulting IEnumerable to an array.

E.g.

Dim filteredList = { a, b,  c }
    .Where(Function(x) x IsNot Nothing)
    .Select(Function(x) x.ToString())
    .ToArray()
Dim result As String = String.Join(" | ", filteredList)

Example: https://dotnetfiddle.net/Epwk3Q

  • Related