After this line:
Author[] author = new Author[5];
all elements of
author
are
null
and not an actual instance of the
Author
class. So the first thing to do when entering the first loop, is creating an instance of
Author
and putting it in the array.
Another problem is that, when creating an
Author
instance, the
book
member is also
null
. When an instance of
Author
is created, you have to assign a value to the
book
property. You can do this using a constructor:
Constructors (C# Programming Guide)[
^]
Another problem is that you try to access an element of
author[i].book
, but that element does not exist yet at index
j
. You first have to add it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Class6
{
static void Main (string[] args)
{
Author[] author = new Author[5];
int bookCount = 3;
for (int i = 0; i < author.Length; i++ )
{
author[i] = new Author();
for (int j = 0; j < bookCount; j++)
{
author[i].book.Add(new Book());
author[i].book[j].Title = "book title";
author[i].book[j].Language = "book language";
}
}
Console.Read();
}
}
public class Author
{
public List<Book> book {get; set;}
public Author()
{
book = new List<Book>();
}
}
public class Book
{
public string Title {get; set;}
public string Language {get;set;}
}
}