Is Convert.toInt32 (boolean) the only way in C # to do this?

I have some code in C # that should increment a number by 1 if a certain boolean value is true, but the same thing should also be said. The only method I found using the Immediate window in VS 2012 is + Convert.ToInt32(boolean).

Am I missing something somewhere in this place? I thought that since the boolean value is mostly true (1) or false (0) (let's forget about FileNotFound), it would be easier to force the boolean value to an Int value.

edit: false - 0, not 1

edit2: my original editing was swallowed. I am currently doing nullcheck on a number (the number is the null int field from the Dynamics CRM 2011 object). Is it possible to keep this nullcheck?

+4
source share
4 answers

I don't think adding a boolean flag to some value is a very readable solution. Basically you want to increase (e.g. add 1) the value if the flag true. So, simply, if the check will clearly describe your intention to add to do the work:

if (flag) value++;

UPDATE: according to your editing you want to do two things:

  • Set the default value to a value with a zero value
  • The value of the increment if any condition is true.

To make your code clear, I would not put both things on the same line. Make your intention explicit:

value = value ?? 0; // 1

if (flag) // 2
    value++;
+6
source

A simple solution would be:

val += flag ? 1 : 0;

, .NET boolean - ( , , ++, "" ). , , . , , (, ) - .

, " ". : true false .

+3

null -check , :

obj.Variable = (obj.Variable ?? 0) + (yourBoolean ? 1 : 0);
//obj is the instance of your object
//Variable is the nullable integer
//yourBoolean is the bool to check against
0

Object.variable - int variable Nullable? Int 0, : Object.variable+=bool?1:0, else : Object.variable=Object.variable??0+bool?1:0

0

All Articles