Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a question mark mean in C# code? [duplicate]

Tags:

operators

c#

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?

like image 649
Alexei Levenkov Avatar asked Mar 28 '17 16:03

Alexei Levenkov


People also ask

What does ?: Mean in C?

It is the "conditional operator". It just happens to be a ternary operator, of which there is only one in C and C++.

What do question marks mean in 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.

How do you use a question mark in coding?

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.

What is the question mark in C sharp?

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)."


1 Answers

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)
like image 186
6 revs, 3 users 77% Avatar answered Oct 09 '22 19:10

6 revs, 3 users 77%