Operator to assign left side only if right side is not null, e.g: =?? #7560
Replies: 5 comments 13 replies
-
I think the claim "more readable" is disputable. |
Beta Was this translation helpful? Give feedback.
-
if =?? is not considered "more readable" than the expanded version, the same argument could be used against "??=" |
Beta Was this translation helpful? Give feedback.
-
There is an existing mechanism for doing this that is genuinely more readable: if (newAvalue is not null and var temporaryA) A = temporaryA; There is a case that And regarding your code example with optional parameters, the simple solution is use overloads rather than optional parameters: class MyClass
{
int Foo {get; init;} = 123;
int Bar {get; init;} = 1234;
public MyClass() { }
public MyClass(int foo) => Foo = foo;
public MyClass(int foo, int bar) : this(foo) => Bar = bar;
} |
Beta Was this translation helpful? Give feedback.
-
Everyone dislikes the suggestion yet you find many people online asking for a simple solution for just that, It's readable and useful. |
Beta Was this translation helpful? Give feedback.
-
What about syntax like that? sureNotNull <<= possibleNull; Alternative of sureNotNull = possibleNull ?? sureNotNull; sureNotNull duplicating can lead to possible errors, when you have to set a lot of values with the same type, just due to typo. |
Beta Was this translation helpful? Give feedback.
-
I often in C# miss the 'opposite' operator of
The obvious syntax would be
As a more readable way to write
(above edited as suggested by @DavidArno)
Or the dirty, but easier to read, variant (that superfluously calls a getter and setter if the new value is null)
Especially useful for e.g. a constructor with optional arguments, where the elements in the class has default values already.
And we only want the defaults overwritten when we actually provide a value for it;
Example
Beta Was this translation helpful? Give feedback.
All reactions