List <T> using inside class

I found sample code about using List inside a class. There are codes that I do not understand. The name and description fields have meaning inside the Define function, but not for the Album field. (

new genre { Name = "Rock" , Description = "Rock music", Album?? }

) Why?

 public class Genre { public string Name { get; set; } public string Description { get; set; } public List<Album> Albums { get; set; } } public class Album { public string Title { get; set; } public decimal Price { get; set; } public Genre Genre { get; set; } } var genre = new List<Genre> { new genre { Name = "Rock" , Description = "Rock music" }, new genre { Name = "Classic" , Description = "Middle ages music" } }; new List<Album> { new Album { Title = "QueensrΓΏche", Price = 8.99M, Genre = genre.Single(g => g.Name == "Rock") }, new Album { Title = "Chopin", Price = 8.99M, Genre = genre.Single(g => g.Name == "Classic") } }; 
+4
source share
4 answers

This C # syntax is called Object and Collection initializers .

Here is the documentation .

This syntax allows you to set properties that you have access to while initializing an object or collection.

+13
source

These are Initializers of objects and collections , which are used to quickly initialize properties. You do not need to initialize all the properties, only those that you need.

+2
source

Because the encoder did not want to set its value. If you want to add an operator at the end of Album = new List (). You do not need to set all the properties.

+2
source

As mentioned by others, sample code uses Object and Collection Initializers . For collections, the Initializer calls the Constructor collector, and then calls the .Add () function for each element specified inside the curly braces. For objects, the initializer calls the constructor of the object, and then sets values ​​for any properties you specify.

Object and collection initializers actually create your object or collection in the temp variable, and then assign the result to your variable. This ensures that you get the result "all or nothing" (i.e. if you cannot get a partially initialized value, if you access it from another thread during initialization). The initialization code can be rewritten as follows:

 var temp_list = new List<Genre>(); // new genre { Name = "Rock" , Description = "Rock music" } var temp_genre_1 = new Genre(); temp_genre_1.Name = "Rock"; temp_genre_1.Description = "Rock music"; temp_list.Add(temp_genre_1); // new genre { Name = "Classic" , Description = "Middle ages music" } var temp_genre_2 = new Genre(); temp_genre_2.Name = "Classic"; temp_genre_2.Description = "Middle ages music"; temp_list.Add(temp_genre_2); // set genre to the result of your Collection Initializer var genre = temp_list; 

Since this code does not explicitly set the Album property value for genres, it gets the default value specified in your Genre class (which is null for reference types).

+2
source

All Articles