Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

c# - If the left operand to the ?? operator is not null, does the right operand get evaluated?

I'm looking at using the ?? operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.

My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As ever, the C# specification is the best place to go for this sort of thing.

From section 7.13 of the C# 5 specification (emphasis mine):

A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.

There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c is evaluated as a ?? (b ?? c)... which means it will only evaluate c if both a and b are null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...