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?
expression cannot be assigned
. I guess one way to think of it is a property without a setter. – Presbyterian