Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a property getter and setter equal something (auto-property initializer)

Tags:

c#

properties

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.

like image 565
Jimmyt1988 Avatar asked Nov 16 '25 19:11

Jimmyt1988


1 Answers

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

like image 97
Mong Zhu Avatar answered Nov 19 '25 08:11

Mong Zhu