Ng-User-JP
Ng-User-JP

Reputation: 23

How to initialize class with list in?

Basic question but I cant find anwser anywhere, I have 2 classes:

public class Book
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string Title { get; set; }
    public IList<Chapter> Chapters{ get; set; }
}

public class Chapter
{
    public int Id { get; set; }
    public string Title { get; set; }
}

How do I add to or initialize this? I have tried:

 var books = new List<Book>();

        books.Add(new Book()
        {
            Id = 1,
            Category = "test",
            Title = "Book1 test",
            Chapters = new Chapter() { Id = 1, Title = "A"},
                       new Chapter() { Id = 2, Title = "B" }
        });

But I'm getting an error: Invalid initializer member declarator?

Upvotes: 1

Views: 105

Answers (3)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

I think you want

Chapters = new List<Chapter>() 
               {
                  new Chapter() { Id = 1, Title = "A"},
                  new Chapter() { Id = 2, Title = "B" }
               }

Instead of:

Answers = new Chapter() { Id = 1, Title = "A"},
          new Chapter() { Id = 2, Title = "B" }
  1. Your Book class doesn't have a property named Answers
  2. You need to create a new collection and place the initializations (new Chapter() { ... }) inside of the collection initializer.

Upvotes: 5

Mike Zboray
Mike Zboray

Reputation: 40818

If you give Book a constructor that initializes Chapters:

public Book
{
    public Book()
    {
        Chapters = new List<Chapter>();
    }

    // properties
}

You will be able to use the collection initializer syntax:

var book = new Book()
{
    Id = 1,
    Category = "test",
    Title = "Book1 test",
    Chapters = { new Chapter() { Id = 1, Title = "A" },
                 new Chapter() { Id = 2, Title = "B" } }
};

Note that if you don't initialize Chapters in the constructor this is still legal, however it will throw a NullReferenceException at runtime.

Upvotes: 1

Prescott
Prescott

Reputation: 7412

Selman22 has one answer. Another might to be initialize the list on instantiation of your object:

public class Book
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string Title { get; set; }
    public IList<Chapter> Chapters{ get; set; }

    public Book()
    {
        Chapters = new List<Chapter>();
    }
}

It's not really an IList anymore, it's just a List. One could always override it though.

Upvotes: 0

Related Questions