0

This is bizarre... I cannot check to see if an object is null in C# because it is null! What is the point in giving me the opportunity to have IsNullOrEmpty and various other checks if I cannot use them? It gives an error telling me that the object is not set to an instance of an object... this is the very reason why I am doing the check!

I am using the Amazon product advertising API and I am trying to get a price. Some of them do not seem to have a price so I need a check to see if the object exists. It then gives me an error for failing INSIDE the actual IF statement check telling me that it is null! That is the very purpose of the check! As an example:

if(String.IsNullOrEmpty(item.ItemAttributes.ListPrice.FormattedPrice))
{
    <p>No Price</p>
}

The only way I can get this to work is by using a try catch. I am being forced to actually produce an exception to get the thing to work. This does not make any sense.

Cheesus Toast
  • 976
  • 2
  • 14
  • 20
  • Because `item` cannot be null, otherwise NRE. And `ItemAttributes` cannot be null, otherwise NRE. And `ListPrice` cannot be null, otherwise NRE. If any of those are null, NRE is thrown before you even get to `FormattedPrice`. Follow the advice in the dupe. Debug. Check to see which element in that call chain is null. Then refactor to check and see if that's null, and handle it appropriately. –  Nov 11 '15 at 15:02
  • That is a very long answer on that one. In fact I do not even think the answer is there on that post but... What you have just said there has actually solved it. I am checking at the wrong point. I simply check at ListPrice before checking at FormattedPrice. When I use the IF statement with simply item.ItemAttributes.ListPrice it is fine. – Cheesus Toast Nov 11 '15 at 15:15
  • @Will's point, though, was that you need to check each one. Otherwise in 6 months you will have the same problem when one of your ItemAttributes is null. Check out C# 6's new null [null propogation operator](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx) if you're curious for an easier way to check. – DrewJordan Nov 11 '15 at 15:23
  • Trust me, the dupe covers this fact. Read it, let it soak in. Understand what and why, and you'll be much better off than you would be if I had simply told you the answer :) –  Nov 11 '15 at 15:28
  • OK I see what you are suggesting. It would be wise to check at each stage in the chain because things (like Amazon PAAPI) are always changing. Makes sense. TY for the links. – Cheesus Toast Nov 11 '15 at 15:43

0 Answers0