1

I have a problem with the development of an application. I am using the eBay API to get information about the items a seller has listed. The Call I use is named "GetSellerList".

The response might contain a value called "CategoryID" (FreeAddedCategory.CategoryID) if there is a FreeAddedCategory available for the item. You would find a XML like this as response:

<ItemArray>
  <Item>
    <FreeAddedCategory>
      <CategoryID>XXXXXXXXX</CategoryID>
    </FreeAddedCategory>
  </Item>
</ItemArray>

Because this value is not always returned I am getting the following error message:

Object reference not set to an instance of an object

I now want to check if this object is available before using it to prevent getting the error. This is how I startet to solve the issue (but without success):

    foreach (ItemType item in apiCall.ApiResponse.ItemArray)
       {
          if (String.IsNullOrWhiteSpace(item.FreeAddedCategory.CategoryID))
                {
                    Console.WriteLine("FreeAdded: Nicht vorhanden!");
                }
        }

But also this check brings up the same error message. What can I do to make the code working? The logic should be like that:

IF item.FreeAddedCategory.CategoryID exist
  {
      do everything that needs to be done
  }
ELSE skip;
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Filz
  • 21
  • 2
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 04 '15 at 16:06
  • Issue is solved. I wrote my solution as a comment below Chuck's answer. And yes, it was a stupid beginners mistake ;) Sorry – Filz May 05 '15 at 15:51
  • @Filz 6 years later and your comment helped me fix my own issue. Thanks!! – hlh3406 Jul 08 '21 at 16:03

1 Answers1

0

Try:

XElement root = XElement.Load(file); // .Parse(string);
if (root.Descendants("FreeAddedCategory").Any())
{
   // do exists
}
else
{
   // doesn't exist
}

Or use CategoryId if that makes more sense for your case.

Chuck Savage
  • 11,775
  • 6
  • 49
  • 69
  • 2
    Hey Chuck, Thanks for you quick reply. My mistake was really stupid! Instead of checking "item.FreeAddedCategory.CategoryID" for "null" I had to check just "item.FreeAddedCategory". Because "item.FreeAddedCategory" had been "null" I did get the NullReferenceException when I tried to access "item.FreeAddedCategory.CategoryID". – Filz May 05 '15 at 15:50