views:

13

answers:

2

my model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace amief.Models
{
    public class WebsiteModels
{
    public static void getPagesForPage(int pageId, dbDataContext db, List<page> myPages)
    {

        var pages = (from p in db.pages
                           where p.pageParent == pageId
                           select p);
        foreach (var item in pages)
        {
            myPages.Add(item);
            getPagesForPage(item.pageId, db, myPages);
        }
    }
}

}

calling the procudure

 List<page> myPages = null;

 WebsiteModels.getPagesForPage(0, db,myPages);

i'm getting an error

System.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object.

on line "myPages.Add(item);"

I don't understand the error...

A: 

You're setting myPages to null before passing it to WebsiteModels.getPagesForPage(). Therefore, the calls to myPages.Add(item); in your loop raise a NullReferenceException because you can't call a method on a null object.

You probably want:

List<page> myPages = new List<page>();
WebsiteModels.getPagesForPage(0, db, myPages);
Frédéric Hamidi
when i remove = null. i get another error : Error Use of unassigned local variable 'myPages'
eyalb
Don't remove `= null`, that only makes your variable `unassigned` (but still `null`). Instead, instantiate a new list of pages as described above.
Frédéric Hamidi
A: 

Well, "myPages" IS null, so calling a method on it results i a NullReferenceException. You should rather write

myPages = new List<page>();
flq