0

This works, calling Invoke only if the member is not null:

List<Command> list = GetCommands();
list.FirstOrDefault(predicate)?.Invoke();

Conditionally calling a property setter does not work:

list.FirstOrDefault(predicate)?.IsAvailable = true;

Instead, an explicit null check must be included:

var command = list.FirstOrDefault(predicate);
if (command != null)
    command.IsAvailable = true;

I'd have thought it makes sense for a setter given it's essentially sytactical sugar for:

list.FirstOrDefault(predicate)?.set_IsAvailable(true);

Is there an inline syntax for setting an object's property conditional on the object not being null?

Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80
  • You can’t use the null-conditional operator as the left side of an assignment. – SᴇM Feb 16 '21 at 05:19
  • _"Instead, an explicit null check must be included:"_ - I don't see anything wrong with that. You can create an extension method if you want. – SᴇM Feb 16 '21 at 05:24
  • Does this answer your question? [Using the null-conditional operator on the left-hand side of an assignment](https://stackoverflow.com/questions/35887106/using-the-null-conditional-operator-on-the-left-hand-side-of-an-assignment) – Charlieface Feb 16 '21 at 05:47
  • Oh, I'm fairly sure the answer is "no". Thanks for the link! I think that is comes down the rules for = operators are different to rules for method calls. – Hand-E-Food Feb 16 '21 at 06:02

0 Answers0