NullReferenceException When Accessing Nested Properties in C# with Auto-Implemented Properties
I'm trying to debug I'm wondering if anyone has experience with I'm working on a project and hit a roadblock. I'm encountering a `NullReferenceException` when trying to access nested properties in a C# class that uses auto-implemented properties. My class structure looks like this: ```csharp public class Customer { public string Name { get; set; } public Address HomeAddress { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } } ``` I'm trying to create a new customer and set the home address, but I'm not initializing the `HomeAddress` property before trying to access its `Street` property. Here's the code where the exception occurs: ```csharp Customer customer = new Customer { Name = "John Doe" }; Console.WriteLine(customer.HomeAddress.Street); ``` This results in a `NullReferenceException`, as the `HomeAddress` is `null` when I attempt to access `Street`. I understand that I need to ensure `HomeAddress` is initialized, but I want to know the best practice to handle such situations. How can I avoid this exception while still keeping the code clean? I've considered using the null conditional operator (`?.`) to safely access properties, like this: ```csharp Console.WriteLine(customer.HomeAddress?.Street); ``` However, this just returns `null` instead of throwing an error, which is not what I want in terms of validation. Is there a way to enforce that `HomeAddress` is not `null` when creating a `Customer`, perhaps through constructor validation or some other design pattern? Any suggestions would be greatly appreciated! Thanks in advance! I'm working with C# in a Docker container on Ubuntu 22.04. Is there a better approach? For context: I'm using C# on CentOS. I'd really appreciate any guidance on this.