How to avoid Nullreference exception when searching in List

Viewed 715

I am trying to get a list item that contains a certain string and I am using this code:

string myListLine= myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("mystring "));

All works well but if the list does not contain a particular string it throws an error:

object reference not set to an instance of an object

I think that I should somehow validate if the string first exists but not sure what would be the best approach.

5 Answers

if the list does not contain a particular string it throws an error:

That is not correct. The exception is thrown, because you have a null value inside your list! If all of your items in the list are valid strings then there will be no exception thrown. In this case FirstOrDefault will simply return null.

I think that I should somehow validate if the string first exists

You can check whether it is null the oldscool way first and combine it with an logical AND && with the Contains method

string myListLine= myList.FirstOrDefault(stringToCheck => 
           stringToCheck != null && stringToCheck.Contains("mystring "));

This way the second Contains will not be evaluated if the first condition evaluates to FALSE

You can use the safe navigation operator and the null-coalescing operator to fix this:

System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string> { null, "Test123" };
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck?.Contains("mystring ") ?? false);

The problem occurs if you're calling a method on a null list entry.

Note: If the list is empty FirstOrDefault returns null.

Hope that helps.

Your code simply goes through myList, for each item, it checks if it contains "mystring ".

Only reason you may get a null reference while running that line is your list myList is null. It wouldn't get any error if it is empty.

if you get a null reference after that line, that would mean that myListLine is null, which would mean myList did not contain any items that matched "mystring ".

To make sure you do not get a null reference error with myListLine you should check if it is null before accessing it by using something like this;

if( myListLine != null ){
    <Do something to myListLine>
} else {
    <list doesnt contain the correct string, alert user.>
}

I think this sample code of mine is one of the safest way by accessing the myList object. If it is null then return an indicator that value was not found or empty.

List<string> myList = new List<string>() 
{
  "name","adress","phoneNumber"
};
myList.RemoveAll(item => item == null);
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("myString")) ?? "Not found/Empty";

A variation:

var myList = new List<string>(){"foo","Bar", null,"the mystring"};
string myListLine = myList.FirstOrDefault(s => s == null? false : s.Contains("mystring"));

Same notes as already mentioned regarding FirstOrDefault being null if empty list or no match (does not Contains)

Related