0

I have a class Store. I need to know what is better way and what is difference in below initialisation.

class Store
{
   // do we initialise List of Item here in property
   public List<Item> Items { get; set; } = new List<Item>();

   public Store()
   {
      // we can instantiate list in constructor 
      Items = new List<Item>();
   }

   public Store(string myString)
   {
      // lets say we have another constructor here and if this one is called
      // than List in default constructor will not be initialised
   }

}
  1. Is it better to initialise List in property?
  2. What is difference between initialisation in property and in constructor?
  3. When property initialisation is called?
  4. On my surprise, I did not initialise List (I commented lines) and it did not throw an error System.NullReferenceException when I created new instance of Store class. Why it did not throw an error if I commented List instantiation. I use VS 2015, could it be automatically in this version.
ExpertLoser
  • 257
  • 4
  • 14

1 Answers1

1
  1. It's better if you want to write less code. There is no difference behind the scene.
  2. The only difference that you can change the order of initialization if you initialize it in constructor. Behind the scene compiler converts your auto-property to the property with backing field and adds initialization of this field in the beginning of all constructors. So, in your code you just overwrite Items property in default constructor.
  3. It's called in constructors (in the beginning).
  4. See p.2

There is also similar question Difference between (auto) properties initialization syntax in C# 6

Community
  • 1
  • 1
chameleon
  • 984
  • 10
  • 15