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:
Set default value to your nullable value
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++;
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.
You can still use the null-check and add the value according to the boolean, like this:
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
Object.variable is int variable OR Nullable? If Int varable it's default value is 0, and you can just write like this: Object.variable+=bool?1:0, else can use it: Object.variable=Object.variable??0+bool?1:0
Related
Hi my question is in the header, i really tried to find how to do this but couldn't find any solution yet, im a newbie so i really need your help guys.
bool a;
bool b;
bool c;
Simply : a,b,c are false : make one true then make false again when others remains false, and make one true again.
There are 3 options: A - B - C, and i want to do 3 things with if statements,
if(a) ....
if(b)....
if(c) ....
so, everytime i need to choose(randomly) only one of them (a or b or c),
From the recent comments, it sounds like what you're actually trying to do is choose randomly between three options. Forget about bools; what you need is simply:
var rand = new Random(); // ideally keep this between uses - maybe a field
//...
switch (rand.Next(3)) // means 0-2
{
case 0: // a
//...
break;
case 1: // b
//...
break;
case 2: // c
//...
break;
}
It is a little unclear what you're asking. I would start by describing the state's you want to represent. If it is "none, a-only, b-only, c-only", then I wouldn't bother with the bools - I'd just use a counter from 0-3, and work from there. You could also use a [Flags] enum with the values 0, 0b001, 0b010 and 0b100 but IMO that is over-complicating things. Another option (if that is unclear) could be an array of tuples of the states you want, for example
new[] {(false,false,true),(false,true,false),(true,false,false)}
This could also be done by using the loop counter as a "left-shift" operand from the literal 1, and using binary arithmetic.
If the states are "all combinations of on/off pairs over 3 bools", then that's just binary integer arithmetic - you'd do a loop from 0-7 and look at the bitwise components of the loop iterator.
If none of this makes sense: maybe try clarifying the question so we can see exactly what you're trying to do - then we can respond with code.
Some context, I'm still rather new at c# but I've been updating c# code that someone else wrote that is incomplete. I've come across this code that seems to be giving me an error.
gblnEnableSSL = Convert.ToBoolean(Convert.ToInt32(Utils.GetSetting("Program", "Configuration", "SSL", "0")));
Utils.GetSetting("Program", "Configuration", "SSL", "0") returns a string "false" currently.
I've found that removing Convert.ToInt32() solves my problem. But, I was unconvinced that someone simply added Convert.ToInt32() that broke the code. I checked in the repo and was surprised to find that the previous code of the same line use to be:
gblnEnableSSL = Utils.GetSetting("Program", "Configuration", "SSL", "0").ToUpper() == "TRUE";
Which seemed to work as well. The checkbox checked value is set by using chkEnableSSL.Value = gblnEnableSSL;
My question is whether or not there is a difference between setting the value using a bool value or a string value. Also, is a difference between chkEnableSSL.value vs chkEnableSSL.Checked?
Edit: I'm not getting a compiler or run-time error with the previous code. It does not perform the code afterwards. For example, i have txtDataSource.Text = strDataSource; immediately after and it does not set the text unless i comment out gblnEnableSSL = ... or remove the Convert.ToInt32().
Edit:Convert.ToInt32() throws an exception but it did not break in VS because i didn't have "Common Language Runtime Exceptions" checked off.
It looks like GetSetting is returning a string. The first code example you gave is converting this string to an integer and then converting it to a boolean. The only way this would work is if the string values stored for that key are either 0 or 1. On your second code block it looks as if the values being used were not string values of 0 or 1 but actual string values of true or false. If the values stored in your config file are still in the format of true or false then this would be why your first line is breaking. You can't convert false or true strings to an int. It does look like someone just added something to break the code.
Also you don't mention what technology you are using. You could be using winforms, wpf, webforms, or MVC. I'm going to assume this is a web technology you are using because checbox.value is something I usually see in javascript. General consensus in setting checkbox values in javascript is by using the .prop() property which takes in a string as the property you want to change and a value as the second parameter. E.G.
$( "input" ).prop( "checked", true );
http://api.jquery.com/prop/
Moral of the story is remove the conversion to the int32 and use .prop() to set that checkbox :)
I want to perform an AND operation. My inputs are 2 objects. It could be a string like "true" or it could be an expression like "1==1" as well. When using && operator, am getting an exception that String was not recognized as a valid boolean.
Please help me.
return Convert.ToBoolean(obj[0]) && Convert.ToBoolean(obj[1]);
Sorry for the earlier post which was not clear enough.
Converting "1==1" to a boolean is not possible for the Convert.ToBoolean method. It just converts the strings true and false.
You will have to either write a expression evaluator yourself, or use some kind of library to parse your string to a boolean (like Flee for example)
First make sure obj[0], obj[1] will only contain 1 or 0(char or integer).
Because Convert.ToBoolean does not understand anything other than 1 or 0.
The below one will work
Convert.ToBoolean(true) && Convert.ToBoolean(1==1)
Why use a string?
The conversion will not evaluate code, it will check if the supplied data is possible to convert to a bool and do so if possible.
Your function will always return true if it was working, cause 1 is always equal to 1, and true is always true.
This is nearly impossible as C# is strongly type language.
What you trying to do is for weakly types languages like JS. "1==1" will work for JS, not for C#.
Remove quotes in order to make it work(You might as well remove first operand, as it doesn't make any sense):
return ( 1 == 1 );
I am try to control multiple strings variables is empty or not at once:
My first approach is very simple:
if(string.isNullOrEmpty(val1) && string.isNullOrEmpty(val2) && string.isNullOrEmpty(val3))
My second way looks like this
if(string.isNullOrEmpty(val1 + val2 + val3))
Which one is fastest and elegant?
Is there any options to do this operation?
The first was faster in my test (just had to): 6ms vs. 70ms and that was on 10,000,000 iterations each (so the speed difference probably doesn't matter very much unless you're doing this on a massive scale).
Anyway, i find the first to be more clear.
Also it doesn't rely on behavior of IsNullOrEmpty that is not immediately obvious (you might just as well think that passing null parameters causes an ArgumentNullException if you don't know better), which i think is important.
Note: The test was with all variables set to null, but setting them to other values confirms it, the longer the strings get, the longer option 2 takes, while option 1 stays at about 30ms max.
Also, the first returns true if any of the strings is null or empty, while the second does it only if all of them are null or empty. So it's not the same check.
They are not equivalent. The first one checks if any of them is null. The second one checks if all of them are null. Make up your mind.
How about this?
new string[] {val1, val2, val2}.All(s => string.IsNullOrEmpty(s))
Or something similar.
I would expect 'fastest' to depend on how often you expect one or more of the strings to actually be null or empty.
For example, if val1 is often going to be null or empty then the first option is likely to be best; if they are all rarely going to be null or empty then I'm not sure of the answer, but it can't take more than five minutes to knock together a few benchmarks for your particular expectations.
(Also, note that the two options don't do the same thing, the first is true if ANY of them are null or empty the second is not doing that)
if(string.isNullOrEmpty(val1 + val2 + val3)) seems to me the fastest
I would advice you to also use concat
but behind the scenes it uses the '+' operator.
I think this is the fastest.
If it werent nullable I suggest summing their length and check ==0
The second one:
if(string.isNullOrEmpty(val1 + val2 + val3))
equals
if(string.isNullOrEmpty(val1) && string.isNullOrEmpty(val2) && string.isNullOrEmpty(val3))
(note the && instead of ||)
but will create an intermediate string, whereas my second version will not create extra strings and stop checking as soon as one string is not empty.
If you have a number of string variables, then I think it is more readable to use the first construction:
if(string.isNullOrEmpty(val1) &&
string.isNullOrEmpty(val2) &&
string.isNullOrEmpty(val3))
{
}
This way, it seems like each variable is treated separately, and this code is a little easier to change if you need to treat one of the variables in another way.
But in case all of the string variables are to be treated in the same way, they are very likely to be represented as an array or another kind of enumeration. Then it's definitely better to use John M Gant's suggestion:
if(myStrings.All(s => string.IsNullOrEmpty(s)))
{
}
I am reading this article on how to work with AD via C#. Half way through the article, the below code is presented.
The user account properties are checkboxes. Does anyone have any idea what the below line of code will return for a checked checkbox? What if more than 1 checkbox is checked? I'd have thought a bool being returned would be more intuitive?
//Add this to the create account method
int val = (int)newUser.Properties["userAccountControl"].Value;
//newUser is DirectoryEntry object
Why do we do the logical or below? How does it work between an int and the second value (is that a byte?)
newUser.Properties["userAccountControl"].Value = val | 0x80000;
//ADS_UF_TRUSTED_FOR_DELEGATION
I know that sounds very naive...
Thanks
The userAccountControl property contains a two byte value in which each single bit has a significant meaning. If the bit is on, then some option is used - if it's not on, then the option is not present.
This is more compact and more space optimized than having a gazillion of booleans. Also, many "older" Win16 and Win32 API just simply work this way.
The bitwise "AND" operator is used to check for the presence of such a single bit:
if (newUser.Properties["userAccountControl"].Value & 0x400 == 0x400)
in this case, the 0x400 bit is set.
In order to actually set a bit, you use the bitwise "OR" operator:
newUser.Properties["userAccountControl"].Value = val | 0x800
This sets the "0x800" bit.
It's basic bit-wise boolean logic, really. A bit messy, indeed - but .NET has some help to make things a bit easier (check out the BitArray data type, for instance)
userAccountControl is a flag field, that's why they put it into an int.
See http://support.microsoft.com/kb/305144 for more information.
Based on the information that you are giving, I would guess that they are using a flags type system to indicate selected items. Each option has a specific value, and they are added up so you can get back which are selected.
This would be proved by the logical or that is used to see if a specific value is included.