Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c# - Null Reference Exception for Class Lists

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 "Object reference not set to an instance of an object" after trying to Add an item to the list I get this error during runtime. I do understand that the List<> reference is null but am trying to understand why it is null and how to get around it. My code will function properly if I just create the List in main but I would like to have it as a class in the future. Like I said I am new to programming OOP and trying to get some information regarding why this is happening. I apologize if this is a repeat question. My code snippet is below:

static void Main(string[] args)
    {
        BookList myBookList = new BookList();

        myBookList.bookList.Add(new Book("The Giver", "Lois Lowry", "Houghton Mifflin"));
        myBookList.bookList.Add(new Book("Telling Lies", "Paul Ekman", "Norton & Company"));
    }


class BookList
{
    public List<Book> bookList { get; set; }
}

class Book
{
    public Book(string title, string author, string publisher)
    {
        Title = title;
        Author = author;
        Publisher = publisher;
    }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Publisher { get; set; }        
}

Thank you, I appreciate all the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...