convert int to bool

  • Thread starter Thread starter John A Grandy
  • Start date Start date
J

John A Grandy

Often in dbs , tinyint is used instead of int (because tinyint cols may be
indexed , whereas int cols may not).

What is the best way to convert integers to booleans ?

The following fails:

bool myBool;
tinyint myTinyInt = 1;

myBool = (bool) myTinyInt;


If you have restricted your integers are restricted to 0 , 1, then the
following works, but is difficult to read:

myBool = (myTinyInt == 1);
 
Hello John A Grandy" johnagrandy-at-yahoo-dot-com,

Second one, (myTinyInt == 1)
Moreover, try to diminish this kind of bool variable and make (myTinyInt
== 1) in the place where do u need true/falce logic
it gives u more robust way.

J> Often in dbs , tinyint is used instead of int (because tinyint cols
J> may be indexed , whereas int cols may not).
J>
J> What is the best way to convert integers to booleans ?
J>
J> The following fails:
J>
J> bool myBool;
J> tinyint myTinyInt = 1;
J> myBool = (bool) myTinyInt;
J>
J> If you have restricted your integers are restricted to 0 , 1, then
J> the following works, but is difficult to read:
J>
J> myBool = (myTinyInt == 1);
J>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
John A Grandy said:
Often in dbs , tinyint is used instead of int (because tinyint cols may be
indexed , whereas int cols may not).

If you are using tinyint for bools then indexing is probably a bad idea.
What is the best way to convert integers to booleans ?

The following fails:

bool myBool;
tinyint myTinyInt = 1;

myBool = (bool) myTinyInt;


If you have restricted your integers are restricted to 0 , 1, then the
following works, but is difficult to read:

myBool = (myTinyInt == 1);

best be safe and use (myTinyInt != 0).

Consider doing the conversion in stored procedures or the query or an
expression column in the DataSet if you use them.
 
In C/C++ all integers different than 0 are considered to be true and all 0s
false. You can use this and convert like

bool myBool = (intValue != 0);

However it depends on your definitial of what is true and false for
integers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top