Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why int.TryParse cannot initialise multiple variables

Tags:

c#

.net

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

like image 241
chxzy Avatar asked Jun 06 '17 09:06

chxzy


People also ask

Does TryParse throw exception?

Parse() method throws an exception if it cannot parse the value, whereas TryParse() method returns a bool indicating whether it succeeded. However, TryParse does not return the value, it returns a status code to indicate whether the parse succeeded and does not throw exception.

What is the use of INT TryParse in C#?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

What is out in TryParse in C#?

What is Out parameter? It is normally used when the method wants to return more than one value. It is a keyword in C# that is used to pass as an argument to a method as a reference type to get value from the method.

What does int TryParse return?

The Int32. TryParse() method returns a boolean value as return and provides the converted value as an out parameter.


Video Answer


1 Answers

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

like image 172
Jon Skeet Avatar answered Sep 25 '22 15:09

Jon Skeet