Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is Convert.toInt32(boolean) the only way in c# to do this?

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?

like image 268
Nzall Avatar asked Jan 11 '23 12:01

Nzall


2 Answers

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:

  1. Set default value to your nullable value
  2. Increment value if some condition is true.

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++;
like image 63
Sergey Berezovskiy Avatar answered Jan 17 '23 15:01

Sergey Berezovskiy


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.

like image 21
Luaan Avatar answered Jan 17 '23 15:01

Luaan