C# Question Mark Operator Nullable, Ternary and Null Combination

1. Nullable type modifier (?):
Reference types can use a null reference to represent a non-existing value, while value types generally cannot represent null.
For example: string str=null; is correct, int i=null; the compiler will report an error.
In order to make the value type also nullable, you can use the nullable type, that is, use the nullable type modifier "?" to represent the form of "T?"
For example: int? for a nullable integer, DateTime? for a nullable time.
T? is actually an abbreviation for System.Nullable (generic structure), which means that when you use T? When the compiler compiles the T? Compile into the form of System.Nullable.
For example: int?, which is in the form of System.Nullable after compilation.

2. Ternary (operator) expressions (?:):
For example: x?y:z means if the expression x is true, return y; if x is false, return z, which is a simple form of omitting if{}else{}.

3. The null coalescing operator (??):
Used to define default values ​​for nullable and reference types. This operator returns the left operand if the left operand of this operator is not null, otherwise returns the right operand.
For example: a??b returns b when a is null, and returns a itself when a is not null.
The null coalescing operator is a right-associative operator, that is, the operation is combined from right to left. For example, the form of "a??b??c" is calculated as "a??(b??c)".

Guess you like

Origin blog.csdn.net/qq_42672770/article/details/124420439