Using the null-conditional operator on the left-hand side of an assignment

diiN__________ picture diiN__________ · Mar 9, 2016 · Viewed 10.7k times · Source

I have a few pages, each with a property named Data. On another page I'm setting this data like this:

if (MyPage1 != null)
    MyPage1.Data = this.data;
if (MyPage2 != null)
    MyPage2.Data = this.data;
if (MyPage3 != null)
    MyPage3.Data = this.data;

Is there any possibility to use the null-conditional operator on MyPage? I'm thinking of something like this:

MyPage?.Data = this.data;

But when I write it like this, I get the following error:

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

I know it's because MyPage could be null and the left-hand side wouldn't be a variable anymore.

It's not that I cannot use it like I have it already but I just want to know if there's any possibility to use the null-conditional operator on this.

Answer

Allmighty picture Allmighty · Mar 9, 2016

The null propagation operator returns a value. And since you must have a variable on the left hand side of an assignment, and not a value, you cannot use it in this way.

Sure, you could make things shorter by using the tenary operator, but that, on the other hand, doesn't really help the readability aspect.

Joachim Isaksson's comment on your question shows a different approach that should work.