Home >Backend Development >C++ >What's the Mystery Behind C# 6.0's Null-Conditional Operator (?.)?

What's the Mystery Behind C# 6.0's Null-Conditional Operator (?.)?

Susan Sarandon
Susan SarandonOriginal
2025-01-25 15:43:11879browse

What's the Mystery Behind C# 6.0's Null-Conditional Operator (?.)?

The secret of C# 6.0 question mark dot operator

The ?. operator introduced in C# 6.0 has sparked interest among developers. Let us unveil its mystery:

What it does:

The

?. operator is called the "empty conditional" operator. It allows you to safely access properties or call methods of a potentially null object without causing annoying NullReferenceException exceptions.

How it works:

?. operator evaluates the first operand. If it is null, the expression stops and returns null. However, if the first operand is not null, then it proceeds to evaluate the second operand, accessed as a member of the first operand.

Example:

Consider the following code snippet:

<code class="language-c#">public class A {
   public string PropertyOfA { get; set; }
}

...

var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
   //somecode
}</code>

Here, if a is null, a?.PropertyOfA will gracefully return null instead of throwing an exception. This allows you to use the string's == operator to compare it to foo and continue executing the if statement without any problems.

Equivalent code:

The

?. operator can be thought of as a shorthand version of the following code:

<code class="language-c#">string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}</code>

Type Notes:

It is worth noting that the ?. operator can also change the type of expression. For example, FileInfo.Length is a property of type long. However, using ?. will result in an expression of type long?:

<code class="language-c#">FileInfo fi = ...; // fi 可能为 null
long? length = fi?.Length; // 如果 fi 为 null,length 将为 null</code>

The above is the detailed content of What's the Mystery Behind C# 6.0's Null-Conditional Operator (?.)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn