Explaination please - variable placement.

  • Thread starter Thread starter estafford
  • Start date Start date
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.
 
Thanks, but I am using C# not VB.NET
IsNumeric does not appear to be available using C#
 
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.
 
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
 
Back
Top