I have the following code that parses some strings into doubles
double number;
double exponent;
if(!double.TryParse(line1, out number) &&
!double.TryParse(line2, out exponent))
throw new ArgumentException("Invalid string");
else
number *= 10.0 * exponent;
I'm getting an error with the compiler that the exponent
is being used when it's not assigned (Use of unassigned local variable 'exponent'). However, I do not get the error with the number
variable even though it's being treated in the same manner. Additionally, the &&
coupled with the out
specifier in the functions being called in the if statement pretty much should guarantee that both number and exponent are assigned by the time it reaches the else block.
The following code DOES compile.
double number;
double exponent;
if(!double.TryParse(line1, out number))
throw new ArgumentException("Invalid string");
else{
if(!double.TryParse(line2, out exponent)){
throw new ArgumentException("Invalid string");
}else{
number *= 10.0 * exponent;
}
}
Why is this the case? In the first code sample, aren't both variables guaranteed to be assigned by the time the else statement is executed? Aren't both code samples equivalent logically? Is this a limitation of the compiler? Actually, I'm kinda surprised the compiler is smart enough to recognize the case in the bottom code sample in the first place.
I'm pretty sure you want ||
instead of &&
. Currently, you're only throwing an exception if both lines are invalid - if the first line is valid, you're never even parsing the second. I assume you actually only want to use number
and exponent
if both of them are valid...
So your code should be (with more idiomatic formatting):
if (!double.TryParse(line1, out number) || !double.TryParse(line2, out exponent))
{
throw new ArgumentException("Invalid string");
}
else
{
number *= 10.0 * exponent;
}
Or to make the whole thing easier to understand, reduce the number of negatives involved - show what you want to do if everything is valid, and handle the negative situations in the else
:
if (double.TryParse(line1, out number) && double.TryParse(line2, out exponent))
{
number *= 10.0 * exponent;
}
else
{
throw new ArgumentException("Invalid string");
}
See more on this question at Stackoverflow