C# 6 Null Conditional idiosynchrasy

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	// The problem: If text is null, this method returns True. I expected False.
	// I had hoped it would short-circuit as soon as null is detected and evaluate the entire expression as false.
    static bool TextContainsWrong(string text)
    {
        return text?.IndexOf('A') != -1;
	}
		
	// Here's what the generated code expands out to:
    static bool TextContainsWrongEquivalent(string text)
    {
        return text == null || text.IndexOf('A') != -1;
	}
	
	// The correct code should be written explicitly like this:
    static bool TextContainsCorrect(string text)
    {
        return text != null && text.IndexOf('A') != -1;
	}	
	
	public static void Main()
	{
		Console.WriteLine(TextContainsWrong(null));
		Console.WriteLine(TextContainsWrongEquivalent(null));
		Console.WriteLine(TextContainsCorrect(null));
	}
}
;