11 May 2020

Operator '&&' cannot be applied to operands of type 'bool' and 'bool?'

How do I fix the compiler error "Operator '&&' cannot be applied to operands of type 'bool' and 'bool?'"
I got this question from a mentee the other day.  They were trying to do the following:

foreach (var user in dbContext.Users.Where(
         u => roles.Contains(targetRole) && 
         u.Valid ?? false == true))
{
   <code...>
}

Unfortunately, they kept getting the compiler error above.  The Valid field in the database is configured as a bit value that is nullable and they want it to return false if it's null.
The fix is straight forward by simply using parentheses thus:

foreach (var user in dbContext.Users.Where(
         u => roles.Contains(targetRole) && 
         (u.Valid ?? false)))
{
   <code...>
}

The double question mark (??) tells C# to return the following value if the preceding is null.  If it isn't null, it will simply process the value as either true or false.

Later
C

No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

Microsoft Authentication Library (MSAL) Overview

The Microsoft Authentication Library (MSAL) is a powerful library designed to simplify the authentication process for applications that conn...