Re: Cannot convert type 'int' to 'bool'

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Registered User wrote:
On Fri, 21 Sep 2007 21:39:26 -0700, John <no@xxxxxxxx> wrote:

The following code:

int test = 1;
bool isTrue = (bool)test;

results in a compiler error:

Cannot convert type 'int' to 'bool'

wtf, any ideas on how to work around this?

bool isTrue = Convert.ToBoolean(test);

You will find that non-zero integer arguments to Convert.ToBoolean all
return true.

regards
A.G.

The Convert.ToBoolean(int) method is implemented as:

public static bool ToBoolean(int value) {
return (value != 0);
}

So it's the same as doing the operation yourself:

bool isTrue = (test != 0);

Perhaps the compiler manages to inline the method call, so that the generated code is the same in both cases. Either way the difference in performance is normally negligable, so you should just go with the one that best describes why you are doing the conversion.

:)

--
Göran Andersson
_____
http://www.guffa.com
.



Relevant Pages

  • Help Please: Passing Functor Object with Template type parameter
    ... I have implemented a generic priority queue below and tested it works ... object of Functor class to cmp, but it got me a compiler error which I ... bool isEmpty() const; ... void buildHeap(); ...
    (comp.lang.cpp)
  • Problems with CAdapt and stl::map
    ... I'm using a stl map to hold a smart pointer as its key value: ... The full text of the compiler error is here: ... while compiling class-template member function ... which will force it to choose the default c++ (bool, ...
    (microsoft.public.vc.atl)
  • Re: Please confirm this is a MSFT bug
    ... The compiler error is correct - you must assign a value to 'Whatever' ... before leaving the method. ... Seems pretty silly and I don't see it as a bug. ... private bool TestThis() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Please confirm this is a MSFT bug
    ... The compiler error is correct - you must assign a value to 'Whatever' before leaving the method. ... bool Continue = ShouldWeContinue; ... public void SomeFunc ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Cannot convert type int to bool
    ... I don't know why you get this error but it could be related with bool values being limited to 1 or 0. ... In this case, the int is 1, but I wouldn't want the compiler trying to determine stuff like that--too much overhead. ... results in a compiler error: ... wtf, any ideas on how to work around this? ...
    (microsoft.public.dotnet.languages.csharp)