jelly
jelly

Reputation: 59

How TryParse method works?

I have the following code.

using System;

class program
{
    static void Main()
    {
        string StrNumber = "100TG";
        int result = 0;

        bool IsConversionSuccessful = int.TryParse(StrNumber, out result);

        if (IsConversionSuccessful)
        {
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine("Invalid");
        }
    }
}

I know that TryParse method tries to convert StrNumber(100TG) into an integer.

And if it succeeds, it's going to save converted value into a result variable and return true for boolean. And if it fails, a result value will remain as 0 and it will return false for boolean.

My question is that no matter what kind of boolean value IsConversionSuccessful variable gets, wouldn't "if(IsConversionSuccessful)" get activated? Am I misunderstanding TryParse Method?

Upvotes: 2

Views: 941

Answers (2)

Joachim Olsson
Joachim Olsson

Reputation: 316

As you clearly have pointed out,

bool IsConversionSuccessful = int.TryParse(StrNumber, out result);

Will set IsConversionSuccessful to true/false based on how the method parsed the number.

If statements in themself evaluate something and always get a boolean answer, true or false. This is because if statements act like binary branch trees. They work like this: enter image description here

When you evaluate if(A), which in your case is

if (IsConversionSuccessful)

The processor decides on a path to take and execution after that depends on the decision the processor made. Note that even excluding the else branch, an empty else branch simply points back to the "..." that comes after the if statement.

Upvotes: 1

Acha Bill
Acha Bill

Reputation: 1255

If IsConversionSuccessful gets to be false, then the condition if(IsConverstionSuccessful) evaluates to if(false). Hence, the body of that if does not execute.

The TryParse method does not determine the execution of the next line in your program. It simply tells you whether the conversion from string to int was successful or not by returning a boolean value.

The lines following TryParse is up to you.

Upvotes: 2

Related Questions