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.

sia
  • 401
  • 3
  • 8
  • 20
  • 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?). –  Dec 28 '11 at 03:27
  • (Is there a generic NullReferenceException post we can close all these as duplicates of? :-/) –  Dec 28 '11 at 03:29
  • http://stackoverflow.com/questions/5620678/nullreferenceexception-no-stack-trace-where-to-start , http://stackoverflow.com/questions/4719047/why-doesnt-nullreferenceexception-contain-information-about-what-is-null , http://stackoverflow.com/questions/1031336/what-is-the-meaning-of-nullreferenceexception –  Dec 28 '11 at 03:32

3 Answers3

6

You need to initialize your list:

private List<book> books = new List<book>();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You need to instantiate books first, like this:

private List<book> books = new List<book>();
Óscar López
  • 232,561
  • 37
  • 312
  • 386
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>();
BILAL AHMAD
  • 686
  • 6
  • 14