2

I'm trying to execute the LINQ to objects query as follows:

var c1 = allCustomers
    .Where(x => x.CompanyName.Replace("'", "").StartsWith(searchText))
    .ToList();

This works fine as long as CompanyName is not null.

So, I thought this seems like the perfect place for the new null conditional operator! Just change to:

var c1 = allCustomers
    .Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText))
    .ToList();

and everything should work!

Instead, I get the error:

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

I'm not quite sure how to accomplish what I want here. How would I use the null conditional in this scenario?

3 Answers 3

5

You need a coalesce operator to convert the tri-state to a proper boolean.

var c1 = allCustomers
    .Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)
    .ToList();

I call bool? a tri-state because it can have three values: true, false and null; therefore, converting bool? to bool is a narrowing conversion that requires explicit treatment.

Sign up to request clarification or add additional context in comments.

Comments

1

you need more question marks! i think you need null coalescing as well, since x.CompanyName?.Replace could now also return null.

(x.CompanyName?.Replace("'", "") ?? string.Empty).StartsWith(searchText))

the ?? string.empty forces that to be a non-null string, which now supports .startswith

3 Comments

ack, i put mine on the string instead of the bool. i think mine will work, but the ?? false versions are better.
Yeah, the other 2 will short circuit on the .? and simply return false.
i interpreted the question tool literally on the "check for null string" part, not on the `bool?' part in the details.
1

Use ?? operator like:

Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)

1 Comment

Could you provide some explanation of why the null-coalescing operator would solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.