chxzy
chxzy

Reputation: 489

why int.TryParse cannot initialise multiple variables

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

Upvotes: 5

Views: 538

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109567

Because if the first int.TryParse(string1, out min) returns false, the second int.TryParse(string2, out max) will not be executed due to boolean short-circuiting.

In that case, max will not have been initialised.

You could just initialise max and min to zero:

int min = 0,
    max = 0;

...

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

Or only use the max and min after checking the result of the && as per other answers.

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

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

If the first int.TryParse(string1, out min) already, the second one will not be executed, as the overall result will already be false. So the max variable is not guaranteed to be always initialized.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

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.)

Upvotes: 7

Related Questions