I have some code in c# which needs to increment a number by 1 if a certain boolean value is true, but else it needs to say the same. The only method i've found using the Immediate window in VS 2012 is by + Convert.ToInt32(boolean)
.
Am I missing something obvious in here somewhere? I thought since a boolean is basically true (1) or false(0) (let's forget about FileNotFound), it would be easier to coerce a boolean to an Int value.
edit: false is 0, not 1
edit2: my original edit got swallowed up. I'm currently doing a nullcheck on the number (the number is a nullable int field from a Dynamics CRM 2011 entity). Is it possible to keep that nullcheck?
I don't think that adding boolean flag to some value is very readable solution. Basically you want to increment (i.e. add 1) value if flag is true
. So, simple if check will clearly describe your intent add do the job:
if (flag) value++;
UPDATE: According to your edit, you want to do two things:
To make your code clear, I would not try to put both things in one line. Make your intent explicit:
value = value ?? 0; // 1
if (flag) // 2
value++;
The simple solution would be like so:
val += flag ? 1 : 0;
The fact is that a .NET boolean is simply a completely different type from integer (unlike in, say, C++, where it's a "renamed" integer). The fact, that it is actually implemented using an integer value, is implementation detail and not to be relied upon. In fact, you can do a lot of strange things when you mess with the actual value of the boolean (for example, using direct memory manipulation or overlapping structure fields) - the consistency goes away.
So, don't work with the "actual value of boolean". Simply expect the two possible values, true
and false
, and work with those.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With