Why int.TryParse can't initialize multiple variables

I am using int.TryParse

to parse variables (stored as strings in a database) and I am curious why I cant initialize 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:

Using the unallocated local variable 'max'

Local variable 'max' cannot 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 without error.

Curious and curious! Any insight was appreciated.

Greetings

+3


source to share


3 answers


Well, you are using &&

that shorts ... if it int.TryParse(string1, out min)

returns false

, the second call int.TryParse

will fail, so max

not definitely assigned.

You can 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 get the body of the statement if

if both calls are made.



Alternatively, you can use the non-short-circuited version with &

instead &&

:

bool lengthCompatible = int.TryParse(string1, out min) &
                        int.TryParse(string2, out max);

      

This is a bit unusual. The advantage of the above version if

is that you retain the performance advantage &&

as you won't try to parse string2

if you don't need to. (Of course, it depends on what you are trying to do).

+6


source


Because if the first int.TryParse(string1, out min)

returns false, the second int.TryParse(string2, out max)

will fail due to the boolean short circuit.

In this case, max

it will not be initialized.

You can just initialize max

and min

to zero:



int min = 0,
    max = 0;

...

bool lengthCompatible = int.TryParse(string1, out min) && int.TryParse(string2, out max);

      

Or use only tags max

and min

after checking the result &&

according to other answers.

+1


source


This is called boolean shortcut evaluation. This ensures that boolean expressions are only evaluated until the final result is found.

If the first one is int.TryParse(string1, out min)

already, the second will not be executed, since the overall result will already be false

. Thus, the variable max

will not always be initialized.

0


source







All Articles