Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Null Reference Exception on List of Strings

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading