none
Return operate doesn't work in IF condition RRS feed

  • Question

  •         public static bool IsInteger(object Input)
            {
                bool Valid = false;
    
                if (Input is string)
                {
                    int Number;
                    while (Valid == false)
                    {
                        if (int.TryParse(Input as string, out Number)) Valid = true;
                        break;
                    }
                    return Valid;
                }
                //int a;
                //int b;
                //if (0 == 0)
                //{
                //    a = 1;
                //    while (a < 10)
                //    {
                //        if (a < 5) b = a;
                //        break;
                //    }
                //    return true;
                //}

    I have declared a method to validate an input as integer. I have return the variable Valid as boolean but the

    compiler still say "all codes path must return a value". In the comment lines I have tried some simple codes with

    the same syntax and it work clearly. I want the return value is in the condition, not outside. If someone can show

    me what I was wrong, that would be appreciated. Thank you.


    Thursday, March 21, 2019 4:15 AM

All replies

  • public static bool IsInteger(object Input)
            {
                bool Valid = false;
    
                if (Input is string)
                {
                    int Number;
                    while (Valid == false)
                    {
                        if (int.TryParse(Input as string, out Number)) Valid = true;
                        break;
                    }
                    return Valid;
                }
               
    
      return Valid;
    }
    Now, all paths return a value
    Thursday, March 21, 2019 4:30 AM
  • I know it has nothing to do with the question, but that 'while' loop is completely superfluous. You could get rid of it and the 'break' statement and the code will work exactly the same.
    Thursday, March 21, 2019 4:50 AM