Null-Conditional Assignment Operator (!?=) #9351
-
Problem:In C#, assigning a value to a property of an object requires an explicit null check if the object might be null, leading to verbose code. For example:
This pattern is common when working with nested objects or nullable references, and it clutters code with repetitive null checks. Proposal:Introduce a null-conditional assignment operator (!?=) that performs an assignment only if the left-hand side is not null. The syntax would look like:
This would be equivalent to: Example:Current code:
With !?=:
This reduces boilerplate and improves readability while maintaining null safety. Benefits:
Discussion:I believe this operator would streamline null-safe assignments and reduce code. Has this been considered before? Are there edge cases or syntax conflicts to address? I’d love feedback from the community and the C# team! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Simply becomes legal in c#14. It's a feature we are already shipping (and have implemented) for that release. |
Beta Was this translation helpful? Give feedback.
obj?.Property.Value = source?.Value;
Simply becomes legal in c#14. It's a feature we are already shipping (and have implemented) for that release.