I know that doing (myValue ?? new SomeClass())
is similar to (myValue == null ? new SomeClass() : myValue)
But out of curiosity, is there any performance benefit when I call a function, say
(getResult() ?? new SomeClass())
. Will getResult()
get executed twice? It seems unintuitive since I've specified the method call only once.
The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result.
In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the name of an item or the default name if the item is null. As you can see, this operator is a handy tool when working with the null-conditional operator.
Nullable types work as a connector between a database and C# code to provide a way to transform the nulls to be used in C# code. Null Coalescing operators simplify the way to check for nulls and shorten the C# code when the developer is dealing with nulls.
C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java.
Well, if by "caching" you mean storing it in a temporary variable, then yes.
This construct:
var result = (getResult() ?? new SomeClass());
can be thought of to be equivalent to this:
var <temp> = getResult();
if (<temp> == null)
<temp> = new SomeClass();
result = <temp>;
This also tells you that the second part, the operand after ??
isn't executed at all if the first operand is not null
.
So to answer your concrete questions:
null
Note also that you can chain these:
var result = first() ?? second() ?? third() ?? fourth();
Which results in:
first()
first()
evaluated to null
, evaluates second()
second()
evaluated to null
as well, evaluates third()
null
, finally evaluates fourth
The result is the first (no pun intended) non-null value returned.
This type of code is about to get even better in new C# with the new ?.
operator:
var result = first?.second?.third;
This is basic .
handling, ie. it will read the second
member of first
, and then the third
member of whatever second
is, but it will stop at the first null
, and will also make sure to evaluate each step only once:
(obj as IDisposable)?.Dispose();
obj as IDisposable
will only evaluate once.
TryGetObjectToSave()?.Save();
Will only call TryGetObjectToSave()
once, and if it returns something, the Save()
method on that something will be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With