Christos Grigoriadis
Christos Grigoriadis

Reputation: 37

TryParse doesnt work for initial values of if statements

I am using TryParse for the code below, but when I put 1 or 2 the program doesnt continue.

int x = -1;
bool noRecords = true;
do
{
    Console.WriteLine("1.Add Data");
    Console.WriteLine("2.Show Data");
    Console.WriteLine("0.Exit");
    //x = Convert.ToInt32(Console.ReadLine());
    if (x == 1)
    {
        Helper.ShowAddMenu(noRecords);
    }
    if (x == 2)
    {
        Helper.ShowDataMenu();
    }
} //while (x != 0);
while (!int.TryParse(Console.ReadLine(), out x) ||  x > 2 || x < 0);

Upvotes: 0

Views: 241

Answers (2)

Michael Gunter
Michael Gunter

Reputation: 12811

Your while loop is wrong if you want it to continue when you enter 1 or 2. The order of operations during execution of that expression in your while loop will be:

  1. You enter the value 1
  2. Console.Readline() will return the string "1"
  3. int.TryParse("1", out x) will set x to 1 and will return true
  4. !true evaluates to false
  5. x > 2 evaluates to false because x is 1
  6. x < 0 evaluates to false because x is 1
  7. therefore, your while loop is while(false || false || false)

EDIT: Given the discussion in the comments below, I believe OPs use case would be best served with a code structure more like the following. Trying to cram it all into the while clause is going to be confusing.

static void Main()
{
    ShowMenu();
    while (true)
    {
        int x;
        if (!int.TryParse(Console.Readline(), out x))
            ShowMenu();
        else if (x == 0)
            break;
        else if (x == 1)
            Helper.ShowAddMenu(noRecords);
        else if (x == 2)
            Helper.ShowDataMenu();
    }
}

static void ShowMenu()
{
    Console.WriteLine("1.Add Data");
    Console.WriteLine("2.Show Data");
    Console.WriteLine("0.Exit");
}

Upvotes: 3

kvr
kvr

Reputation: 573

Change !int.TryParse to just int.TryParse. TryParse returns true on success, not false.

See here dotnetfiddle.net/6JCoPQ

Upvotes: 0

Related Questions