title: Variable not within scope using HttpWebRequest and WebResponse
body: <p>I am having an issue with my variable httpRes. Basically this is the basics of a command line app that will check a set of given URL's and return their status code, i.e. unauthorized, redirect, ok etc. The problem is one of the apps within my list keeps throwing an error. So I used a try catch clause to catch the error and tell me what caused it.</p>
  
  <p>Unfortunately the variable httpRes works in the try clause, but not in the catch. It keeps being returned as null. I called httpRes outside of the try/catch statement so I am hoping my scope is correct but for whatever reason the value never changes from null for the catch statement, only the try statement.</p>
  
  <p>Here is the code referenced.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Net;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace URLMonitor
  {
      class Program
      {
          static void Main(string[] args)
         {
              string url1 = "https://google.com"; //removed internal URL for security reasons.
              HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url1);
              httpReq.AllowAutoRedirect = false;
              HttpWebResponse httpRes = null;
  
              try
              {
                  httpRes = (HttpWebResponse)httpReq.GetResponse();
                  if (httpRes.StatusCode == HttpStatusCode.OK)
                  {
                      Console.WriteLine("Website is OK");
                      // Close the response.
                      //httpRes.Close();
                  }
              }
              catch
              {
                  if (httpRes != null)
                  {
                      if (httpRes.StatusCode == HttpStatusCode.Unauthorized)
                      {
                          Console.WriteLine("Things are not OK");
                          //httpRes.Close();
                      }
                  }
                  else
                  {
                      Console.WriteLine("Please check the URL and try again..");
                      //httpRes.Close();
                  }
              }
              Console.ReadLine();
  
          }
      }
  }
  </code></pre>