November 18, 2020

Conditional Null Operator ?.

expression1?.expression2  => expression1 != null ? expression2 : null
This expression evaluates to: expression2, if expression1 is Not-Null. else, it evaluates to null
What happens when a conditional operator is inside a boolean expression?
void Main()
{
    A a = new A();
    if (a?.BVal?.Value == 4)
	{
	    Console.WriteLine("boolean expression returns true");
	}
	else
	{
		Console.WriteLine("boolean expression returns false"); // This line is output
	}
}

public class B
{
   public int Value { get; set; }
}

public class A
{
   public B BVal { get; set; }
}
A related operator is ??=
variable ??= expression // if (variable is null) { variable = expression; }