Anthony Darden
Anthony Darden

Reputation: 127

Array check: Object reference not set to an instance of an object

I am struggling to find a solution to this problem. I see lots of simlilar entries on this site that touch upon this subject, but I can't seem to arrive at a solution. I am trying to check a table in cache to see if it already exists and if not, populate it. Below is my code for that check and it errors on the 'if' statement telling me 'System.NullReferenceException: Object reference not set to an instance of an object'. This is puzzling because shouldn't the '.IsNullOrEmpty' catch this? I figure if the 1st element in the array is null or empty then it hasn't been cached yet and therefore take action.

            string[] saveCatList = Cache["Categories" + Session["sessopnID"]] as string[];
            if (string.IsNullOrEmpty(saveCatList[0]))
            {
                WBDEMOReference.getcatlist_itemcategories[] categories;
                strResult = callWebServ.getcatlist(Session["sessionID"].ToString(),
                            out strResultText, out dNumOfCat, out categories);

                for (int i = 0; i < categories.Length; i++)
                {
                    //ddCat is the ID number of the category drop down list
                    ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(),
                                                 categories[i].categorynumber.ToString()));
                }
            }

Upvotes: 1

Views: 2343

Answers (3)

Tilak
Tilak

Reputation: 30718

Change

if (string.IsNullOrEmpty(saveCatList[0]))

To

if (saveCatList != null && saveCatList.Length>0 && string.IsNullOrEmpty(saveCatList[0]))

Also, Change

  ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(),
                                             categories[i].categorynumber.ToString()));

To

if (categories[i].categorydesc != null && categories[i].categorynumber!= null)
{
  ddCat.Items.Add(new ListItem(categories[i].categorydesc.ToString(),
                                             categories[i].categorynumber.ToString()));

}

Upvotes: 0

tmesser
tmesser

Reputation: 7666

Cache["Categories" + Session["sessopnID"]] as string[];

This cast is failing and 'as string' is returning null. Therefore, when you try to access the associated variable as an array, you're essentially doing null[0], which is a NullReferenceException.

If you add a check to first ensure that the array is not null this will work fine.

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27604

With string.IsNullOrEmpty(saveCatList[0]) you check if first element of array is empty or null. It seems that your array is null, so you should firstly check your array:

if(saveCatList == null || string.IsNullOrEmpty(saveCatList[0]))

Upvotes: 5

Related Questions