I've seen code like the following unrelated lines:
Console.Write(myObject?.ToString());
return isTrue ? "Valid" : "Lie";
return myObject ?? yourObject;
int? universalAnswer = 42;
There seems to be more in C#8+ like
public static Delegate? Combine(params Delegate?[]? delegates)...
string? value = "bob";
Are all of the usages of the question mark related or different? What do each of them mean?
It is the "conditional operator". It just happens to be a ternary operator, of which there is only one in C and C++.
The question mark operator, ?:, is also found in C++. Some people call it the ternary operator because it is the only operator in C++ (and Java) that takes three operands. If you are not familiar with it, it's works like an if-else, but combines operators.
The question mark operator ? takes three operands: some condition, a value if that condition is true, and a value if that condition is false. It is used in JavaScript to shorten an if else statement to one line of code.
It's the null conditional operator. It basically means: "Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
Question marks have different meaning in C# depending on the context.
The Null-Conditional Operator (MSDN, What does the question mark in member access mean in C#?)
Console.Write(myObject?.Items?[0].ToString());
The Conditional Operator/Ternary Operator (MSDN, Benefits of using the conditional ?: (ternary) operator)
return isTrue ? "Valid" : "Lie";
The Null Coalescing Operator (MSDN, What do two question marks together mean in C#?)
return myObject ?? yourObject;
Nullable Value Types (MSDN, What is the purpose of a question mark after a type (for example: int? myVariable)?)
int? universalAnswer = 42;
Nullable Reference Types C# 8 added nullable reference types with many more options to sprinkle question marks (it also gave new place to put explanation marks - null!" is a null-forgiving operator):
Nullable string (remember that string
is reference type behaving like value type):
string? value = "bob";
Nullable array of nullable reference objects - What is the ?[]? syntax in C#?
public static Delegate? Combine(Delegate?[]? delegates)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With