2

What's the difference between:

public List<MyType> Something{ get; set; } = new List<MyType>();

and

public List<MyType> Something{ 
    get{
        return new List<MyType>();
    }
    //set...
}

Context:
I'm unsure of the behaviour I'm seeing in my code. A service is there on constructor, but null on a future method call in the what I assume is the same instance of the class.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233
  • What reason for the down vote :) ? Straight to the point, Only included what was needed for the question, searched for whatever i could find regarding it but do not know the words to search correctly for it. Not sure what else i could have done here to make the question better? Plus i got the answer within seconds. – Jimmyt1988 Aug 21 '18 at 10:44
  • 2
    Could be because the code does not compile. `'Something.set' must declare a body because it is not marked abstract, extern, or partial` – fredrik Aug 21 '18 at 10:46
  • Thanks @fredrik - I've updated the Q for future peeps. – Jimmyt1988 Aug 21 '18 at 10:47
  • 3
    You could have easily debugged this behavior by adding a break point, a that point you *should* have noticed the `return new List();` being called every time you accessed the getter. Also you should have include *why* you were asking the question, I presume because maybe you were not seeing the content of the list being persisted. – Igor Aug 21 '18 at 10:47
  • My issue was related to the instantiation of a service that was there once, but not there a second time. So was confused by the difference/behaviour. That's why i came here. Thanks for your input though @Igor – Jimmyt1988 Aug 21 '18 at 10:48
  • "but null on a future method call in the what i assume is the same instance of the class." that is indeed strange behaviour. something else inside the class that sets the service to `null` inbetween? – Mong Zhu Aug 21 '18 at 11:01

1 Answers1

8

The first line:

public List<MyType> Something{ get; set; } = new List<MyType>();

will be called once when the object (that has this property) is instantiated. It is a one time creation of an instance of Something.

The second example is an explicit implementation of the getter. Every time you access the getter of Something it will return a new and empty list.

EDIT:

The first line is called an auto-property initializer for a detailed answer have a look at a post by Jon Skeet. This feature exists since C# 6.0

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76