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 -=
So, my question is - what and I misunderstanding about null-propagation? Why is this not a permitted syntax?
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.
Expression (which null propagation operator always returns) can not be used as left part of assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With