Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Access expression cannot be assigned - C# null-propagation += events

One of my favorite C# features added is the "null-propagation" in CS6.

This has cleaned up so much code for many of us.

I came across a situation where this doesn't appear to be possible. I am not sure why as I though the null-propagation was just some compiler magic that does some null checks for us, allowing us to maintain cleaner code.

In the case of hooking into events..

 public override void OnApplyTemplate()
    {
        _eventStatus = base.GetTemplateChild(PART_EventStatus) as ContentControl;

        // This not permitted and will not compile
        _eventStatus?.IsMouseDirectlyOverChanged += EventStatusOnIsMouseDirectlyOverChanged;

        // but this will work
        if(_eventStatus != null) _eventStatus.IsMouseDirectlyOverChanged += EventStatusOnIsMouseDirectlyOverChanged;

        base.OnApplyTemplate();
    }

    private void EventStatusOnIsMouseDirectlyOverChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        throw new NotImplementedException();
    }

Compile output shows:

 error CS0079: The event 'UIElement.IsMouseDirectlyOverChanged' can only appear on the left hand side of += or -=

Resharper Complaint

So, my question is - what and I misunderstanding about null-propagation? Why is this not a permitted syntax?

like image 475
TravisWhidden Avatar asked Aug 01 '17 22:08

TravisWhidden


2 Answers

This is by design. The null propagation operator allows to propagate nulls while evaluating an expression, but it cannot be used as the target of an assignment.

Think of it this way: The operator returns a value. However, you need a variable on the left-hand side of the assignment. Having a value there wouldn't make sense.

An issue was opened about this, and is currently open as a feature request. The reply we got at the time was the following:

The ?. Operator never produces an lvalue, so this is by design.

like image 53
stelioslogothetis Avatar answered Oct 13 '22 00:10

stelioslogothetis


Expression (which null propagation operator always returns) can not be used as left part of assignment.

like image 37
Pavel Aschepkov Avatar answered Oct 13 '22 01:10

Pavel Aschepkov