m-albert
m-albert

Reputation: 1100

ReSharper Wants To "Optimize" My Code

Does the following...

    SomeType _someProperty;
    public SomeType SomeProperty
    {
        get
        {
            if (_someProperty == null)
                _someProperty = new SomeType();
            return _someProperty;
        }
    }

...have the same functionality as the following?

    SomeType _someProperty;
    public SomeType SomeProperty
    {
        get { return _someProperty ?? (_someProperty = new SomeType()); }
    }

According to ReSharper they do. And if so, can someone please explain the syntax of the second block?

Upvotes: 3

Views: 172

Answers (4)

David L
David L

Reputation: 33823

Yes, they are the same functionality.

?? is the null coalescing operator. The operator returns the value before the operator if not null, or the value after the operator if the preceding value is null.

In this case, by wrapping the second part of the expression in params, you are assigning a new object to the _requiredFieldValidator backing field before returning it if __requiredFieldValidator is null.

If you did not have the parentheses, you would not assign before returning, which results in the following compile-error:

The left-hand side of an assignment must be a variable, property or indexer

The parentheses guarantee that the assignment expression is evaluated correctly.

Upvotes: 9

Evk
Evk

Reputation: 101473

I think most confusion here comes not from ?? operator. Just many people do not know that Assignment operator in C# returns right-hand value as it's result.

Upvotes: 4

Dave Zych
Dave Zych

Reputation: 21887

Yes, they are the same. ?? is the Null Coalescence Operator, which checks the first operand against null, and if it's null then returns/runs the second operand.

The second code block says "Return _someProperty if it's not null. However, if it is null, then set _someProperty = new SomeType() and return that."

Upvotes: 4

Eric J.
Eric J.

Reputation: 150108

Yes they are the same.

?? is the null coalescing operator. If the operand on the left hand side of ?? is not null it will use that thing, otherwise it will use the operand on the right hand side.

In your case it will return _requiredFieldValidator if it is already initialized, otherwise it will initialize it first then return it.

Upvotes: 4

Related Questions