Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> using inside a class

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") }
};
like image 791
Goran Zooferic Avatar asked Dec 02 '22 19:12

Goran Zooferic


2 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 during initialization of the object or collection.

like image 155
Davin Tryon Avatar answered Dec 10 '22 11:12

Davin Tryon


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.

like image 45
Toni Petrina Avatar answered Dec 10 '22 11:12

Toni Petrina