Why doesn't instantiating an object automatically instantiate its properties?

Viewed 742

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";
2 Answers

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();
}

One of the reasons that child objects are not automatically instantiated is that you may not want to call the default constructor, or even you want to force the programmer to call the constructor with enough parameters to correctly initialise the class fully, so there isn't a public default constructor.

You could argue that if there is a default constructor then it should always run, followed by the one you actually want, but then you are doing the same work twice.

public class CustomerResult
{
   public string CompanyStatus { get; set; }
   public OverallResult Result { get; set; }
}

public class OverallResult
{
   public OverallResult()
   {
       StatusCode = 55;
       StatusDescription = "Nothing to see";
   }
   public OverallResult(int statusCode, string status)
   {
      StatusCode = statusCode;
      StatusDescription = status;
   }
   public string StatusDescription { get; set; }
   public int StatusCode { get; set; }
   public string CustomerId { get; set; }        
}

void main()
{
   var result = new CustomerResult()
   {
       Result = new OverallResult(51, "Blah"),
   };
}
Related