0

I'm getting a null reference exception with this on the line below when I try to add what is a regular string to a list. I added the extra .

   PhotoUrls.Add(images[i].GetAttribute("href").ToString());

Even though when I hover over it in the debugger it is showing it as a string with a value in that line. Here's the full method for context.

  public static List<String> Process()
    {
        List<String> PhotoUrls = null;

        try
        {
            WaitForReady(driver, TimeSpan.FromSeconds(2));
            driver.ExecuteScript("window.scrollTo(0,4000);");
            var images = driver.FindElementsByCssSelector(".v1Nh3 a");
            

            for (int i = 0; i < images.Count; i++)
            {
                
                PhotoUrls.Add(images[i].GetAttribute("href").ToString());
            }

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        return PhotoUrls;

    }

1 Answers1

0

You list is not initialized. So when you call Add on a null object, a null reference occurs.

public static List<String> Process()
    {
        // Changed this line here
        List<String> PhotoUrls = new List<String>();

        try
        {
            WaitForReady(driver, TimeSpan.FromSeconds(2));
            driver.ExecuteScript("window.scrollTo(0,4000);");
            var images = driver.FindElementsByCssSelector(".v1Nh3 a");
            

            for (int i = 0; i < images.Count; i++)
            {
                
                PhotoUrls.Add(images[i].GetAttribute("href").ToString());
            }

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        return PhotoUrls;

    }
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Ah thank you! I had spent all day losing my mind over this. I thought - List PhotoUrls = null; was enough to initialize. – Tim Stevens Feb 25 '21 at 13:38