Why is the null conditional operator not allowed for property assignment?

386 views Asked by At

I just noticed that property assignment is not allowed in combination with the null conditional operator. With methods is it not a problem at all though.

I always thought that properties are just syntactic sugar for setter methods.

item?.SetMarker(Marker.Start); // Perfectly fine
item?.Marker = Marker.Start; // Error   CS0131  The left-hand side of an assignment must be a variable, property or indexer

So why is one allowed and the other not?

I'm pretty sure there is a good theoretical reason. With the small hope of getting smarter I just try to know why :)

PS - I noticed the same behaviour in TypeScript.

1

There are 1 answers

0
Sajjad Mortazavi On

In the second line, when item is null, it does not have any Marker, so you are not able to assign any value to it.

On the other hand, In the first line, when item is null, SetMarker method is not even called and in another word you do not try to assign anything.