Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Nullreference exception when searching in List [duplicate]

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.

like image 818
Cat Hariss Avatar asked Jan 20 '26 15:01

Cat Hariss


2 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

like image 62
Mong Zhu Avatar answered Jan 22 '26 06:01

Mong Zhu


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.

like image 39
Moerwald Avatar answered Jan 22 '26 05:01

Moerwald