How to Avoid NullReferenceException When Accessing Nested Properties in C# with Optional Chaining?
I tried several approaches but none seem to work. I'm experimenting with I'm trying to configure I'm reviewing some code and I'm encountering a `NullReferenceException` when I'm trying to access nested properties of an object in my C# application. I have the following class structure: ```csharp public class User { public Profile Profile { get; set; } } public class Profile { public Address Address { get; set; } } public class Address { public string City { get; set; } } } ``` I have a method that retrieves a `User` object, and I want to safely access the `City` property of the `Address`. Hereβs the code Iβm currently using: ```csharp public string GetUserCity(User user) { return user.Profile.Address.City; } ``` However, if either `Profile` or `Address` is null, I get a `NullReferenceException`. I tried checking for null explicitly like this: ```csharp public string GetUserCity(User user) { if (user?.Profile?.Address != null) { return user.Profile.Address.City; } return "Unknown"; } ``` This works, but it feels verbose, and Iβm concerned about maintainability. I heard about the optional chaining feature introduced in C# 8.0, but Iβm not sure how to use it effectively in this case. Could someone show me how to implement optional chaining to simplify my code? Additionally, are there any best practices for handling such cases, especially when dealing with deep property access in larger projects? I'm working with C# in a Docker container on Windows 10. Thanks in advance! For reference, this is a production desktop app. I'd love to hear your thoughts on this.