1

I am checking a HtmlDocument() by html id called shippingMessage_ftinfo_olp_1 but problem is that i am unable to check if this is a null exception. Because when i set if !=null still it throws exception. Anyone can tell me how can i check it if its null without this exception?

System.NullReferenceException: 'Object reference not set to an instance of an object.'

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(response);
string gerLang = "";
if (htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1").InnerText != null)
{
    gerLang = htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1").InnerText;
    if(gerLang.Contains("AmazonGlobal Express-Zustellung"))
    {
        _outOfStock = false;
    }
}

pic

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
john Cogdle
  • 1,423
  • 2
  • 16
  • 26
  • you messed up the title -> Cocument – Cerike Sep 15 '18 at 10:52
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Kirk Larkin Sep 15 '18 at 10:56
  • Someone will be along soon to close this out as a duplicate of the question I've linked. However, you want to check that `htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1") != null` before you check the `InnerText`. – Kirk Larkin Sep 15 '18 at 10:59
  • When someone dont know the solution, its a way to mark as duplicate with a source manual book! Good job but the great guy not hesitate to answer as i selected bellow – john Cogdle Sep 15 '18 at 11:14
  • I also voted your question as a duplicate of that question, but provided an answer as a community wiki answer to help you solve your exact problem :-) (not to say that Kirk didn't also provide a solution above). – ProgrammingLlama Sep 15 '18 at 11:15
  • Real solution is so quick just put `?` anywhere you dont trust! haha thanks to mark as duplicate also! – john Cogdle Sep 15 '18 at 11:16

1 Answers1

1

Use a null conditional operator:

if (htmlDoc.GetElementbyId("shippingMessage_ftinfo_olp_1")?.InnerText != null)

If htmlDoc can be null, also change that to htmlDoc?.GetEle....

Reasoning: A null conditional operator short-circuits the evaluation if the object being evaluated is null, preventing you from getting an exception, in favour of evaluating to null.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86