I am new to programming and am running into an issue when creating a class with a list property of another class and then accessing it in main. I am getting the exception \"
When you create BookList
, you haven't actually initialized the list that is its member. You can do this by changing your initialization to:
BookList myBookList = new BookList() {bookList = new List<Book>()};
Or by writing a constructor for the BookList
class which initializes the list; which would look like this:
class BookList
{
public List<Book> bookList { get; set; }
public BookList(){ //New constructor
bookList = new List<Book>();
}
}
The reason you get this error is that while you've created an instance of BookList, you haven't actually make sure that the BookList
's inner booklist
property is initialized. It's like if you tried to do this:
List<string> newList;
newList.Add("foo");
That wouldn't work because you've only declared the newList
, not initialized it.
Your problem is with public List<Book> bookList { get; set; }
in your BookList
class; you've never initialized it. You can do this, for example, from within the constructor:
class BookList
{
public List<Book> bookList { get; set; }
public BookList
{
bookList = new List<Book>();
}
}
Please note: properties should always be named with Pascal casing, i.e. all letters uppercase: BookList
not bookList
.
Also, since it doesn't really make sense to replace your BookList
with another instance of List<Book>
, I would suggest you set the access modifier on the setter to private
so it can only be initialized once, i.e. in the constructor:
public List<Book> bookList { get; private set; } // notice the "private" set
You need to initialize the Boolist.bookList
in the default ctor
:
class BookList
{
public BookList() { bookList = new List<Book>; } // <<<<
public List<Book> bookList { get; set; }
}