The .? operator is a mechanism for handling potentially null objects more safely, avoiding null pointer exceptions, similar to TypeScript and Swift, which have similar mechanisms.
When using .?, if the accessed object is null, the entire expression is null and no exception is thrown; otherwise, it is accessed normally.
Example#
For safe access:
In this case, if person or person.Address is null, the entire expression will return null; otherwise, it will return the value of person.Address.City. This avoids the NullReferenceException that would occur when directly accessing person.Address.City if person or person.Address is null.
Common Scenarios#
- Method calls:
- Event handling:
// todo Event handling
- Element access:
// todo ?
- Combined with
??to provide a default value:
// todo ??