Explaination please - variable placement.

E

estafford

Newbie looking for some insight here.
I am writing a block to check limitations on a query string as follows:

public bool validNumber(string qstring){
bool isValidNumber;
foreach(char c in qstring){
if(!Char.IsNumber(c)){
isValidNumber = false;
break;
}
else{isValidNumber = true;}
}
return isValidNumber;
}

This however returns a compiler error: - CS0165: Use of unassigned local
variable 'isValidNumber' - at the "return isValidNumber" line.
But if I move the second line [isValidNumber decleration] outside of the
function, it works fine.

Why does this happen if I am only using the variable within the function?

And if anyone has an easier way of checking a number only value, I'd sure
like to know.

Thanks for any help with this.
 
E

estafford

Thanks, but I am using C# not VB.NET
IsNumeric does not appear to be available using C#
 
S

Steven Campbell

estafford said:
Newbie looking for some insight here.
I am writing a block to check limitations on a query string as follows:

public bool validNumber(string qstring){
bool isValidNumber;
foreach(char c in qstring){
if(!Char.IsNumber(c)){
isValidNumber = false;
break;
}
else{isValidNumber = true;}
}
return isValidNumber;
}

This however returns a compiler error: - CS0165: Use of unassigned local
variable 'isValidNumber' - at the "return isValidNumber" line.
But if I move the second line [isValidNumber decleration] outside of the
function, it works fine.

Why does this happen if I am only using the variable within the function?

And if anyone has an easier way of checking a number only value, I'd sure
like to know.

Thanks for any help with this.
All you have to do is assign isValidNumber a value when declaring it, i.e.
bool isValidNumber = false; //default value

PS, I would have written it like this, to avoid the temporary variable
altogether:
public bool validNumber(string qstring){
foreach(char c in qstring)
{
if(!Char.IsNumber(c))
return false;
}

return true;
}

Another technique could be to try "int.Parse(qstring)". If the parse
works, then it is a number, and if it gives an exception then it is not.
 
E

estafford

I also should mention that I did try your data type suggestion and that
works great.
I didn't realize such a simple solution was available.

I spent hours sifting through the .NET and C# info in the SDK and MSDN.
Thanks for your help.

ES
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top