Home > Mobile >  C# 7.5/9.0 Operators priority - try to find a complete summary
C# 7.5/9.0 Operators priority - try to find a complete summary

Time:09-23

We are using the last version of c#. We need the complete table of Operators priority, but we can't find it.

For example, what's the priority here?

string c = a ?? string.Empty   "example";

where a is a string.

CodePudding user response:

(Credit for the link goes to Bill Tür, who answered in a comment.)

For example, what's the priority here?

The search term you are looking for is operator precedence.

The operator precedence is documented in the C# language reference, currently found at:

Regarding your concrete example, appears earlier in the list than ?? and, thus, has a higher precedence. This means that

a ?? b   c

is evaluated as

a ?? (b   c)

Note to address a common misconception: Operator precedence does not affect the order of evaluation: a is still evaluated before both b and c. Operands in C# are always evaluated left-to-right.

CodePudding user response:

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

So, in your case, a will be checked if it's null or not. in case a is null, c will be assigned with the string "example". if a is not a null, c will be assigned with the a string value.

If you're used to ternary operators, you can translate:

string c = a ?? string.Empty   "example";

to:

string c = a != null ? a : string.Empty   "example";
  • Related