Null Reference Exception for Class Lists

后端 未结 3 1305
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 05:16

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 \"

3条回答
  •  清歌不尽
    2020-12-12 05:38

    Your problem is with public List 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 bookList { get; set; }
    
        public BookList
        {
            bookList = new List();
        }
    }
    

    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, 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 bookList { get; private set; } // notice the "private" set
    

提交回复
热议问题