What does a question mark mean in C# code?

23,703

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)
Share:
23,703
Alexei Levenkov
Author by

Alexei Levenkov

Alexei Levenkov is developer at Microsoft. I use http://bing.com as my search engine.

Updated on August 05, 2022

Comments

  • Alexei Levenkov
    Alexei Levenkov over 1 year

    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?