Working with the null conditional operator

Tests involving the null conditional operator (?) introduced in C# 7.

Tests the value of the left-hand operand for null before performing a member access. The null-conditional operators are short-circuiting. If one operation in a chain of conditional member access and index operations returns null, the rest of the chain's execution stops.

void Main()
{
	Test t = null;
	if(t?.Id > 5)
	{
		Console.WriteLine("tick");
	}else{
		Console.WriteLine("tock");
	}
}

class Test{
	public int Id { get; set; }
}

Output: tock

Without the null conditional operator, the operation will result in a NullReferenceException.

The expression t?.Id > 5 is equivalent to t != null && t.Id > 5

Latest Updates

© 0 - 2025 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com