By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,933 Members | 1,574 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,933 IT Pros & Developers. It's quick & easy.

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

P: 1
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
Oct 18 '08 #1
Share this Question
Share on Google+
4 Replies


Ganon11
Expert 2.5K+
P: 3,652
You are probably using if statements or a loop, in which you try and use an integer to determine the truth value. For instance:

Expand|Select|Wrap|Line Numbers
  1. int myFunction(int a, int b) {
  2.    if (a < b) return -1;
  3.    if (a == b) return 0;
  4.    if (a > b) return 1;
  5. }
  6.  
  7. // ...later in your code...
  8.  
  9. if (myFunction(3, 5)) {
  10.    // ...
  11. }
  12.  
  13. // OR
  14.  
  15. while (myFunction(x, 3)) {
  16.    // ...
  17. }
C and C++ allow this, maybe C# doesn't?
Oct 18 '08 #2

Expert 10K+
P: 11,448
I'm moving this thread over to the .NET forum where the C# questions are posted.

kind regards,

Jos (moderator)
Oct 18 '08 #3

P: 50
Please post the piece of code where the exceptiong is thrown
Oct 18 '08 #4

tlhintoq
Expert 2.5K+
P: 3,525
You are probably using if statements or a loop, in which you try and use an integer to determine the truth value. For instance:

Expand|Select|Wrap|Line Numbers
  1. int myFunction(int a, int b) {
  2.    if (a < b) return -1;
  3.    if (a == b) return 0;
  4.    if (a > b) return 1;
  5. }
  6.  
  7. // ...later in your code...
  8.  
  9. if (myFunction(3, 5)) {
  10.    // ...
  11. }
  12.  
  13. // OR
  14.  
  15. while (myFunction(x, 3)) {
  16.    // ...
  17. }
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.

Expand|Select|Wrap|Line Numbers
  1. 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
Expand|Select|Wrap|Line Numbers
  1. if (myFunction(3,5) != 0)
  2. {
  3.  // Then do this
  4. }
Otherwise, you can change myFunction to return a bool depending on the conditions.
Oct 19 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.