0

I can write:

_myVariable?.SetValue(5);

It will call SetValue only if _myVariable is not null, fine.

How can I do the same thing with a Property ? Like (caution, this syntax does not exists):

_myVariable?.Value = 5;

Since it does not exists (please contradict me), I have to use that good old if syntax :

if (_myVariable is not null) _myVariable.Value = 5;

Property setters and Set functions are, in fact, the same thing except syntax, so I feel upset about this difference.

Do you have any syntax in mind better than good old if ?

KiwiJaune
  • 530
  • 2
  • 16
  • 2
    If `_myVariable?.Value` evaluates to `null`, what would you be setting? – Johnathan Barclay Nov 25 '21 at 15:40
  • The assignation is converted to a method call eventually. But like @JohnathanBarclay mentioned the behavior become really complicated if you see it from the side of where the assignation is going to when the object is null. – Franck Nov 25 '21 at 15:45
  • And even worse: What does that say about your logic _if_ you need to set a value on something that in fact _is_ null? Isn't there a bigger design issue? – Fildor Nov 25 '21 at 15:48
  • 1
    It currently isn't possible, but it is being worked on: [relevant github issue](https://github.com/dotnet/csharplang/issues/2883) – Jeroen Verfaillie Nov 25 '21 at 15:55
  • 1
    Relevant or duplicate question here https://stackoverflow.com/questions/35887106/using-the-null-conditional-operator-on-the-left-hand-side-of-an-assignment – Steve Nov 25 '21 at 16:02

0 Answers0