2

I'm trying this code:

private List<book> books;
//private book[] books;
.
.
.
private void button1_Click(object sender, EventArgs e)
        {
            books.Add(new book(book_name.Text));
            //book[0]=new book(book_name.Text);
        }

but I'm getting this error:

'Object reference not set to an instance of an object.'

What should I do? I want dynamic creation of object by an event.

3
  • 1
    Read the error message, love the error message. That particular error means you are doing expr.member, where expr evaluates to null. In this case that is books because it was never assigned a value (a new List, perhaps?). Commented Dec 28, 2011 at 3:27
  • (Is there a generic NullReferenceException post we can close all these as duplicates of? :-/) Commented Dec 28, 2011 at 3:29
  • stackoverflow.com/questions/5620678/… , stackoverflow.com/questions/4719047/… , stackoverflow.com/questions/1031336/… Commented Dec 28, 2011 at 3:32

3 Answers 3

6

You need to initialize your list:

private List<book> books = new List<book>();
Sign up to request clarification or add additional context in comments.

Comments

2

You need to instantiate books first, like this:

private List<book> books = new List<book>();

Comments

0

when you say

private List<book> books;

It only creates a reference of type List with null value. So when you try to call the member function of the List structure, it gives an error that the reference is set to null.

You need to initialize the variable using another statement in the constructor

books = new List<book>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.