Kevin
Kevin

Reputation: 4848

Why can't I add objects to my List<>?

I have a class, clsPerson, that looks like this:

public class clsPerson
{
    public string FirstName;
    public string LastName;
    public string Gender;
    public List<Book> Books;
}

I have another class, Book, that looks like this:

public class Book
{
    public string Title;
    public string Author;
    public string Genre;        

    public Book(string title, string author, string genre)
    {            
        this.Title = title;
        this.Author = author;
        this.Genre = genre;
    }
}

I wrote a program to test serializing an object into XML. Here's what I have, so far:

class Program
{
    static void Main(string[] args)
    {
        var p = new clsPerson();
        p.FirstName = "Kevin";            
        p.LastName = "Jennings";
        p.Gender = "Male";

        var book1 = new Book("Neuromancer", "William Gibson", "Science Fiction");
        var book2 = new Book("The Hobbit", "J.R.R. Tolkien", "Fantasy");
        var book3 = new Book("Rendezvous with Rama", "Arthur C. Clarke", "Science Fiction");

        p.Books.Add(book1);
        p.Books.Add(book2);
        p.Books.Add(book3);

        var x = new XmlSerializer(p.GetType());

        x.Serialize(Console.Out, p);
        Console.WriteLine();
        Console.ReadKey();
    }
}

I'm getting an error, though, in VS2013 that says "NullReferenceException was unhandled" on line p.Books.Add(book1);.

Obviously, I'm doing something wrong. I thought that I could create a few books and then add them to my clsPerson object's List called Books. I can't figure out why the error is saying 'NullReferenceException' when the book1 object was just instantiated prior to me trying to add it to my Books list. Can someone offer me a pointer or some advice?

Upvotes: 1

Views: 10585

Answers (3)

rhughes
rhughes

Reputation: 9583

You should really initialize your objects when creating them in a class.

Try this:

public class clsPerson
{
    public string FirstName;
    public string LastName;
    public string Gender;
    public List<Book> Books = new List<Book>();
}

Upvotes: 3

Cam Bruce
Cam Bruce

Reputation: 5689

You are not instantiating your Books collection in your Person class

In your Person constructor:

public Person()
{
  this.Books = new List<Book>();
}

Upvotes: 8

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You should initialize your list first:

if(p.Books == null)
   p.Books = new List<Book>();

It is more appropriate to do it in your clsPerson class constructor.

Upvotes: 5

Related Questions