NullReferenceException ERROR in foreach loop using HTMLNode

c#, foreach, html-agility-pack, nullreferenceexception

Solution

if(imagegallery != null && imagegallery.DocumentNode != null){
  foreach (HtmlNode link in 
    imagegallery.DocumentNode.SelectNodes("//a[@href]") 
      ?? Enumerable.Empty<HtmlNode>()) 
  {
    //do something
  }
}

Problem

How do I catch the NullReferenceException Error in the foreach loop below if 'SelectNodes' returns NULL? I searched on stackoverflow and found mention of the null-coalescing condition (?? condition) that can be used to catch this error, however, I have no idea on what the syntax would be for HTMLNode, or if that's even possible. ``` foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@href]") ) { //Do Something } ``` How would you cath the NULL EXCEPTION for this loop, or is there a better way of doing this? Here is the full code throwing the exception - ``` private void TEST_button1_Click(object sender, EventArgs e) { //Declarations HtmlWeb htmlWeb = new HtmlWeb(); HtmlAgilityPack.HtmlDocument imagegallery; imagegallery = htmlWeb.Load(@"http://adamscreation.blogspot.com/search?updated-max=2007-06-27T10:03:00-07:00&amp;max-results=20&amp;start=18&amp;by-date=false"); foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@imageanchor=1 or contains(@href,'1600')]/@href")) { //do something } } ```

Original source