When using a null-conditional operator the first if statement will always output True, however the second if statement will output False when using parentheses. Why is the first if statement True?
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var test = new Test { Boolean = true };
//True
if (test?.Boolean ?? true && 1 == 2)
Console.WriteLine("True");
else
Console.WriteLine("False");
//False
if ((test?.Boolean ?? true) && 1 == 2)
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
public class Test
{
public bool? Boolean { get; set; }
}
}
x ?? y – returns x if it is non-null; otherwise, returns y.
test?.Boolean is x in the first case and (true && 1 == 2) is y.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments