Cannot implicitly convert type 'int' to 'bool' ?????

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hellomac23
    New Member
    • Oct 2008
    • 1

    Cannot implicitly convert type 'int' to 'bool' ?????

    Hi im trying to write a if...else for C# but i keep getting Cannot implicitly convert type 'int' to 'bool' i really lost can anybody help me on what that means
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    You are probably using if statements or a loop, in which you try and use an integer to determine the truth value. For instance:

    Code:
    int myFunction(int a, int b) {
       if (a < b) return -1;
       if (a == b) return 0;
       if (a > b) return 1;
    }
    
    // ...later in your code...
    
    if (myFunction(3, 5)) {
       // ...
    }
    
    // OR
    
    while (myFunction(x, 3)) {
       // ...
    }
    C and C++ allow this, maybe C# doesn't?

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      I'm moving this thread over to the .NET forum where the C# questions are posted.

      kind regards,

      Jos (moderator)

      Comment

      • SvenV
        New Member
        • Oct 2008
        • 50

        #4
        Please post the piece of code where the exceptiong is thrown

        Comment

        • tlhintoq
          Recognized Expert Specialist
          • Mar 2008
          • 3532

          #5
          Originally posted by Ganon11
          You are probably using if statements or a loop, in which you try and use an integer to determine the truth value. For instance:

          Code:
          int myFunction(int a, int b) {
             if (a < b) return -1;
             if (a == b) return 0;
             if (a > b) return 1;
          }
          
          // ...later in your code...
          
          if (myFunction(3, 5)) {
             // ...
          }
          
          // OR
          
          while (myFunction(x, 3)) {
             // ...
          }
          C and C++ allow this, maybe C# doesn't?
          You're on the right track. In C++ a zero is false, and anything not zero is true.
          C# doesn't work that way. You need to actually have boolean responses of true and false.

          Code:
          if (myFunction(3, 5)) {
          really says " if (value returned from myFunction(3,5) is true) { ... }"
          But your method return an int, not a bool. So the error message complaining "I don't know how to convert your returned int into a bool." makes sense.

          You need a boolean as the final evaluation of your if (....) statement.
          Try something like this if myFunction will continue to return an int
          Code:
          if (myFunction(3,5) != 0)
          {
           // Then do this
          }
          Otherwise, you can change myFunction to return a bool depending on the conditions.

          Comment

          Working...