Alex Rivera | Logout

C# can't cast bool to int

Asked 2009-06-03T19:31:59.417
45

We all know that in C# we can't cast bool to int. I wanted to see what is the binary representation of true with bitmask, but I can't use (bool & int).. I think the problem is the architecture desicion "true is true, not any number != 0" (C++) and I was wondering what the benefits of such an architecture are? What is so bad with the C true/false concept?

Edit
Report

2 Answers

5

I don't think the issue is some much about true/false or 1/0 as it is about the decision to make C# a strongly-typed language rather than a weakly-typed language. There are many benefits (and some drawbacks) to a language being strongly typed. One of the benefits is that it reduces bugs due to misuse (or incorrect use) of expressions.

For example,

int i = 0;
if (i = 1) {
   ...
}

won't even compile in C#, but it will both compile and execute incorrectly in C.

Choosing to make C# a strongly-typed language infers these benefits to C# programmers. Even so, they could have introduced a conversion from bool to int (and back) if they choose. I suspect that they didn't do so due to the potential for bugs like that above to be introduced.

answered 2009-06-03T19:41:41.910
-2

You make a good point on these. However it does remove one shortcut.

With c, toggles can be easily done by the code "bBool = 1 - bBool".

If bBool is true (1), then 1 - 1 = 0. bBool changes to false.

If bBool is false (0), then 1 - 0 = 1. bBool changes to true.

Instead in C# I'm required to do a conditional to check the state, and then set it to it's opposite, which causes more work for the machine and me.

answered 2010-04-30T22:52:56.260

Your Answer