string inside IF statement is showing an error like it is not decared.

  • Thread starter Thread starter tdmailbox
  • Start date Start date
T

tdmailbox

I had some code that returns a random record for a recordset. It works
fine unless my record set has one value. So as a solution I tried to
wrap the whole thing inside an If statement so that it was only called
if the record count was bigger then 1.

However when I made that I change I get the error that "The name
'strHTMLPage' does not exist in the class or namespace." If appears
that if my variable is declared inside the If statement it throws and
error each time the variable is called further down in the application.

Any idea how I can fix this?

-----
Random randObj = new Random(DateTime.Now.Second);
int num = randObj.Next(alURL.Count - 1) + 1;
string strHTMLPage = readHtmlPage(alURL[num].ToString());

----------
Random randObj = new Random(DateTime.Now.Second);
if (alURL.Count > 1)
{
int num = randObj.Next(alURL.Count - 1) + 1;
string strHTMLPage = readHtmlPage(alURL[num].ToString());
}
else
{
string strHTMLPage = readHtmlPage(strURL);
}
 
However when I made that I change I get the error that "The name
'strHTMLPage' does not exist in the class or namespace." If appears
that if my variable is declared inside the If statement it throws and
error each time the variable is called further down in the application.

....because when you leave the block, the variable goes "out of scope".
Any idea how I can fix this?

Declare the variable outside the blocks...

Random randObj = new Random(DateTime.Now.Second);

string strHTMLPage = null;

if (alURL.Count > 1)
{
int num = randObj.Next(alURL.Count - 1) + 1;
strHTMLPage = readHtmlPage(alURL[num].ToString());
}
else
{
strHTMLPage = readHtmlPage(strURL);
}

// Bjorn A
 
Yes, except declare the string

string strHTMLPage;

Do not initialize it to null, as this will defeat the compiler's check
to make sure that it's initialized it before you use it.
 
Back
Top