[Solved] do-while loop does not go through while condition C#


The problem is that you return the inputed string at the end of the loop no matter the validation done.

You can use a boolean to check this validity.

Also you don’t need to parse all the string and you can break the inner loop on the first invalid char.

I renamed the string as result to use a standard pattern and to be more clean.

For example:

static string GetUserString(string letters)
{
  string result;
  bool isValid;
  do
  {
    Console.Write("Enter : ");
    result = Console.ReadLine();
    isValid = true;
    foreach ( char c in result )
      if ( letters.IndexOf(char.ToUpper(c)) == -1 )
      {
        isValid = false;
        Console.WriteLine("Enter a valid input");
        break;
      }
  }
  while ( !isValid );
  return result;
}

1

solved do-while loop does not go through while condition C#