?. operator (null coalescing operator) is used to safely access properties or methods that may be null, avoiding NullReferenceException, simplifying code and improving readability. It will return the value of the property or method if present, otherwise it returns null.
The ?. operator in C
#What is the ?. operator?
?. operator (also known as the null coalescing operator) is a C# operator used to safely access a property or method that may be null.
How to use the ?. operator?
To use the ?. operator, place it before a property or method that may be null. If the property or method is not null, the operator returns its value. Otherwise, it returns null.
For example:
<code class="csharp">Person? person = null; // person 可能为 null string name = person?.Name; // 如果 person 不为 null,则返回 name 属性;否则,返回 null</code>
?. Benefits of the operator:
The main benefits of using the ?. operator are:
Example:
The following example demonstrates how to use the ?. operator in C#:
<code class="csharp">class Person { public string Name { get; set; } } Person? person = null; // 使用 ?. 运算符安全地访问 Name 属性 string name = person?.Name; // 如果 person 不为 null,则打印 name;否则,打印 "Person is null" Console.WriteLine(name ?? "Person is null");</code>
Output:
<code>Person is null</code>
The above is the detailed content of What does ? in c# mean?. For more information, please follow other related articles on the PHP Chinese website!