Вопрос

Here is my piece of code using the Int32.TryParse with if condition.(console application)

Console.WriteLine("Enter the no of the person(value for n)");
string number = Console.ReadLine();            
Console.WriteLine("Enter the no of the bulb whose state you want to check(value for x)");
string bulbNumber = Console.ReadLine();           
if ((Int32.TryParse(number, out n)) || (Int32.TryParse(bulbNumber, out x)))
{
}

if we check the value for n in quickwatch, then it correctly captures the value you input , but if you check the value for x, it is surprisingly 0!!! - Any ideas how to overcome this? I wonder what is causing this anomaly.

Это было полезно?

Решение 2

of course the value of x is 0, after parsing to n you already got a "true" in your or condition, so the second tryparse will never be executed. if you want to make sure both are parseable use an and condition:

if ((Int32.TryParse(number, out n)) && (Int32.TryParse(bulbNumber, out x)))

Другие советы

You should use && rather than ||, "||" is saying if one is true, which one is so it ignores the second. Using && both must be true.

if ((Int32.TryParse(number, out n)) && (Int32.TryParse(bulbNumber, out x)))
{
      //Go crazy
}

Your original code meant that it would do this:

First tryparse || Second tryparse

First completed > straight into if statement, ignores second as one has passed.

With the && it says both MUST be true.

For further information on this you can use MSDN to see examples of the differences in the conditional statements:

&& operator

|| operator

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top