You are writing a boolean expression that might look like this:
team.Category == "A Team" && team?.Manager?.IsVietnamVet
public class Manager
{
public bool IsVietnamVet { get; set; }
}
public class Team
{
public string Category { get; set; }
public Manager Manager { get; set; }
}
...and you get an error:
Operator '&&' cannot be applied to operands of type 'bool' and 'bool?'
What is the optimal/cleanest way to handle it?
team.Category == "A Team" && (team?.Manager?.IsVietnamVet ?? false)Is that really readable?
team.Category == "A Team" && (team?.Manager?.IsVietnamVet).GetValueOrDefault()It may not work in LINQ-to-Entities...
team.Category == "A Team" && team?.Manager?.IsVietnamVet == trueWould you really write
if (condition == true)without any hesitation?
Are there any other options? Is it ultimately better to write:
team.Category == "A Team" && team.Manager != null && team.Manager.IsVietnamVet
team.Manager?.IsVietnamVet, i.e. no null conditional afterteam, since already can't benull.nullableBool == trueis basically testing fornullableBool != false && nullableBool != null(and it's this second part that makes it useful and therefore not superfluous)nullableBool == trueif I don't create a wrapper. It is readable because you normally don't write== truewhen using regular boolean as @Flater mentions, so it suggests that the variable is nullable. Aditionally, it improves LINQ readability because you don't use multiple null conditions as @Fabio mentions.