Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

instance

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";
like image 553
levis84 Avatar asked Dec 01 '22 14:12

levis84


1 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();
}
like image 93
D-Shih Avatar answered Dec 05 '22 06:12

D-Shih