How to avoid null in IF

Jassim Al Rahma 1,616 Reputation points
2022-07-25T09:19:12.503+00:00

Hi,

I have the following line that checks with IF when typing in a Searchbox control:

if (list.flight_iata.ToLower().Contains(searchBar.Text.ToLower()) || list.status.ToLower().Contains(searchBar.Text.ToLower()))  

How can I determine null value and resume without error if null is found?

Thanks,
Jassim

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. ShuaiHua Du 636 Reputation points
    2022-07-25T16:27:50.94+00:00

    Add an extension method:

    namespace System  
    {  
        public static class StringExtensions  
        {  
            public static string SafeTrim(this string value, params char[] trimChars)  
            {  
                if (value == null)  
                {  
                    return string.Empty;  
                }  
                else  
                {  
                    return value.Trim(trimChars);  
                }  
            }  
        }  
    }  
      
    

    Update your IF condition as below:

    if (list != null &&(list.flight_iata.SafteTrim().ToLower().Contains(searchBar.Text.ToLower()) || list.status.SafteTrim().ToLower().Contains(searchBar.Text.ToLower())))  
    

    The SafeTrim() method will return a string.Empty if the specified string is null.

    If right, please Accept.
    Enjoy Programming!!!

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-07-25T20:05:13.89+00:00

    or just use c#

     if (list.flight_iata?.ToLower().Contains(searchBar.Text?.ToLower() ?? "") ?? false  
     || list.status?.ToLower().Contains(searchBar.Text?.ToLower() ?? "") ?? false)  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.