Say I have the following code here:
static void Main(string[] args)
{
StringBuilder[] s = new StringBuilder[3];
if (s[0]?.Length > 0)
{
Console.WriteLine("hi");
}
}
My understanding is that the expression that goes inside the if statement, must be a boolean expression. A boolean expression (my understanding I could be wrong) is an expression that evaluates to true or false.
In this case, the null-conditional operator will return null since, the default value of an element within an array of reference-type variables, is null. Therefore, this if statement is equivalent to
bool? x = null;
if (x)
{
// do cool things here */
}
But this gives me a syntax error: cannot convert null to bool.
Therefore, how it is possible that the above example with StringBuilder works? My understanding that the better approach to the code above should be to combine it with null-coalescing operator, as in:
if (s[0]?.Length > 0 ?? false) {}
Thanks all :)