Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

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

Writer Matthew Harrington

Trying to read a dataContext class like this

var users = new List<User>();
var roles = new int[] { 1, 2 };
// here I need to get users who's role is in role (1, 2), hence above line
// and also I need to get user who's isValid field true, please note that isValid is SQL 'bit' field and is nullable
//This is what I am doing
foreach (var user in dataContext.Users .Where(u => roles.Contains(u.RoleID.Value) && u.isValid ?? false == true)) // here '&&' part I'm struggling and getting above error
{ users.Add(new User() { // Users Added in collection });
}

So the question is in where clause I need to get user's who are in role(1,2) && isValid == true, if isValid is 'null' make it false. Thanks

1

3 Answers

You have to wrap it in parentheses:

roles.Contains(u.RoleID.Value) && (u.isValid ?? false)

bit of confused with (u.isValid ?? false), does this not mean that if u.isValid == null then make it false and look for users where u.isValid is false, this is not what I want.

No, it just means that nulls are treated as false and that all users are taken which isValid is neither null nor false. It works because the ??-operator converts the Nullable<bool> to a bool, so you can use it with &&. I don't like it, i prefer explicit code that i understand later:

roles.Contains(u.RoleID.Value) && u.isValid.HasValue && u.isValid.Value

or simpler by using the ==-operator with the bool?:

roles.Contains(u.RoleID.Value) && u.isValid == true
4

Given bool will default to false anyway you could use GetValueOrDefault

roles.Contains(u.RoleID.Value) && u.isValid.GetValueOrDefault()

Note - GetValueOrDefault does not appear to be supported by EF - see ticket

5

You can try like this.

 foreach (var user in dataContext.Users .Where(u => roles.Contains(u.RoleID.Value) && (u.isValid ?? false))) // note the bracket around (u.isValid ?? false)

Or

foreach (var user in dataContext.Users .Where(u => roles.Contains(u.RoleID.Value) && (u.isValid.HasValue && u.isValid))) //you can use HasValue to check for null
6