Unexpected NullReferenceException When Accessing Nested Properties in a C# 9 Record
I'm following best practices but Quick question that's been bugging me - I'm working on a project and hit a roadblock... I'm working with a `NullReferenceException` when trying to access properties of a nested object within a record type in C# 9. I've defined a nested record for a user profile, and when I try to access a property of this nested object, it occasionally throws the exception even though I believe it should be initialized. Here's the structure of my records: ```csharp public record Address(string Street, string City); public record UserProfile(string Name, Address? HomeAddress); public class UserService { public void PrintUserAddress(UserProfile user) { // This line throws NullReferenceException intermittently Console.WriteLine(user.HomeAddress.Street); } } ``` In my application, I construct a `UserProfile` like this: ```csharp var user = new UserProfile("John Doe", null); var userService = new UserService(); userService.PrintUserAddress(user); ``` Since I'm using a nullable `Address` in the `UserProfile`, I expected to handle cases where `HomeAddress` might be `null`. I've tried checking for null explicitly before accessing the `Street` property, but it seems like the behavior occurs even when I think I'm handling the null case properly. Hereโs the safer approach I implemented: ```csharp public void PrintUserAddress(UserProfile user) { if (user.HomeAddress != null) { Console.WriteLine(user.HomeAddress.Street); } else { Console.WriteLine("Address not provided."); } } ``` However, this doesnโt seem to solve the scenario. The `NullReferenceException` still creeps in at times. I suspect it might be due to some other part of my codebase modifying the state of the `UserProfile` instance unexpectedly, but I canโt trace it. Any insights on how to diagnose and fix this scenario? What best practices should I follow when dealing with nested records and nullable properties in C# 9? For context: I'm using C# on Windows. Thanks in advance! This is happening in both development and production on Debian. I'm working with C# in a Docker container on Ubuntu 20.04. What's the correct way to implement this?