I am using int.TryParse
to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:
int min,
max;
using the following conditional statement:
bool lengthCompatible = int.TryParse(string1, out min) &&
int.TryParse(string2, out max);
Visual Studio (2015) produces the following code highlighting:
Use of unassigned local variable 'max'
Local variable 'max' might not be initialized before accessing
However, if I use 2 conditional statements:
bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);
I can compile with no errors.
Curiouser and curiouser! Any insight appreciated.
Cheers
Well you're using &&
, which is short-circuiting... if int.TryParse(string1, out min)
returns false
, the second call to int.TryParse
won't be made, so max
isn't definitely assigned.
You could write:
if (int.TryParse(string1, out min) &&
int.TryParse(string2, out max))
{
// Use min and max here
}
... because then the compiler knows that you only reach the body of the if
statement if both calls have been executed.
Alternatively you could use the non-short-circuiting version with &
instead of &&
:
bool lengthCompatible = int.TryParse(string1, out min) &
int.TryParse(string2, out max);
That's slightly unusual though. The advantage of the if
version above is that you'll retain the performance benefit of &&
, in that you won't bother trying to parse string2
if you don't need to. (It depends on exactly what you're trying to do, of course.)
See more on this question at Stackoverflow