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.
Null-conditional operators ?. and ?[] Available in C# 6 and later, a null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null; otherwise, it returns null . That is, If a evaluates to null , the result of a?. x or a?[x] is null .
Introduced in C# 6.0, the Null Conditional Operator ?. will immediately return null if the expression on its left-hand side evaluates to null , instead of throwing a NullReferenceException . If its left-hand side evaluates to a non- null value, it is treated just like a normal .
In certain computer programming languages, the Elvis operator, often written ?: , or or || , is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand.
The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows: C# Copy.
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.
As Joachim Isaksson suggested in the comments, I now have a method SetData(Data data)
and use it like this:
MyPage1?.SetData(this.data); MyPage2?.SetData(this.data); MyPage3?.SetData(this.data);
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