I found a code sample about using List inside a class.There are codes what i don't understand.Name and Description fields have value inside List defination but Album field have not a value.(
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") }
};
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 during initialization of the object or collection.
Those are Object and Collection Initializers which are used for quick initialization of properties. You don't need to initialize all properties, just the ones you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With