I have the following classes:
public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; }
}
public class OverallResult
{
    public string StatusDescription { get; set; }
    public int StatusCode { get; set; }
    public string CustomerId { get; set; }        
}
I instantiate:
var apiResult = new CustomerResult();
Why does the following return a null reference? Surely OverallResult is instantiated when I create CustomerResult()?
apiResult.Result.CustomerId = "12345";
                Because you didn't create an instance for Result. Reference types have null values by default and OverallResult is a class, hence a reference type.
You can do it in constructor.
public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; }
    public CustomerResult(){
        Result = new OverallResult();
    }
}
if your C# version heigher than 6.0 there is a simpler way Auto-Property Initializers
C# 6 enables you to assign an initial value for the storage used by an auto-property in the auto-property declaration:
public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; } = new OverallResult();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With