Set an object's property conditional on the object not being null

369 views Asked by At

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?

0

There are 0 answers