john Cogdle
john Cogdle

Reputation: 1533

How to handle HtmlDocument null exception

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

Upvotes: 1

Views: 270

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38785

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.

Upvotes: 1

Related Questions