C operator? ? ? ? Usage and explanation of various question marks

  • 2021-09-16 07:44:19
  • OfStack

1. Nullable type modifier (? ): A reference type can use a null reference to represent a value that does not exist, whereas a value type cannot normally be represented as null, for example: string str=null; Is correct. int i = null; The compiler will report an error. In order to make the value type nullable, nullable types appear, and nullable types use nullable type modifiers? To express, the expression form is T? . Example: int? Indicates nullable shaping, DateTime? Represents as nullable time. T? It's actually System. Nullable < T > The abbreviation of (generic structure), which means that when you use T? Will the compiler put T at compile time? Compiled into System. Nullable < T > For example: int? When compiled, it is System. Nullable < int > The form of.


int a; //a<>null
int ?b; //b=null
int ?c = b+1; //c=null;

2. Empty merge operator (? ? ): Default values for defining nullable and reference types. If the left operand of this operator is not null, the operator returns the left operand; Otherwise, the right operand is returned. Example: a? ? b, b is returned when a is null, and a itself is returned when a is not empty. An empty merge operator is a right merge operator, that is, a right-to-left combination when operating. For example, the form of "a?? b?? c" is calculated as "a?? (b?? c)".


int?a=null; int b;( Declaration a And b)
b=a??2; //b=2;
a=6;b=a??8;//b=6;

3, 3 yuan (operator) expression (? :): If you don't understand this either (I don't believe it very much), then you can pretend that I don't understand it either, and don't repeat it.


int a=1>0?1:0 //a=1;


Related articles: