Reputation: 23
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
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" }
Book
class doesn't have a property named Answers
new Chapter() { ... }
) inside of the collection initializer.Upvotes: 5
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
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