Share via

How to avoid NULL here?

Anonymous
2021-10-14T21:32:57.69+00:00

Hi,

I have this if code:

if (list.category_name.ToLower().Contains(searchBar.Text.ToLower()) || list.sub_category_name.ToLower().Contains(searchBar.Text.ToLower()) || list.search_keyword.ToLower().Contains(searchBar.Text.ToLower()))

but it keeps throwing null error when any of the fields is null.

my class is like this:

public string search_keyword { get; set; }

Kindly help..

Developer technologies | .NET | Xamarin
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

P a u l 10,766 Reputation points
2021-10-14T21:46:17.813+00:00

You can just check each field before you use them:

if (list.category_name != null && list.category_name.ToLower().Contains(searchBar.Text.ToLower())
    || list.sub_category_name != null && list.sub_category_name.ToLower().Contains(searchBar.Text.ToLower())
    || list.search_keyword != null && list.search_keyword.ToLower().Contains(searchBar.Text.ToLower()))

Or you could use the null-conditional operator if you prefer that:

if (list.category_name?.ToLower().Contains(searchBar.Text.ToLower() == true)
    || list.sub_category_name?.ToLower().Contains(searchBar.Text.ToLower() == true)
    || list.search_keyword?.ToLower().Contains(searchBar.Text.ToLower()) == true)

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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