c# data class members are instantiated at declaration

37 views Asked by At

I am working on a project where a lot of the data classes look like this:

[DataMember]
public List<SpecialOpeningHours> SpecialOpeningHours { get; set; } = new List<SpecialOpeningHours>();

I've never seen this before and would normally just do this:

[DataMember]
public List<SpecialOpeningHours> SpecialOpeningHours { get; set; }

Can anyone explain why the list in instantiated in this way and whether or not there is some advantage? It doesn't seem to make any difference in use. I am using Dapper and get the same result populating the list either way.

1

There are 1 answers

3
MakePeaceGreatAgain On BEST ANSWER

Your first example is just a shortcut introduced on C#6 for this:

public MyClass()
{
    this.SpecialOpeningHours = new List<SpecialOpeningHours>();
}

Now compare this with:

public MyClass()
{
    this.SpecialOpeningHours = null;
}

The former is what your first option is translated into when compiling, the second one is what you get when you don“t add any initial value. In particular your second example will cause a NullReferenceException as soon as you call any of its members, whereby the first one will run fine.