Boolean to integer conversion - c#

Is there a way to covert from bool to integer without a conditional statement (e.g., if-statement)?
int intValue = boolValue ? 1 : 0;

No, there is not. You may hide this conditional behind additional method calls like Convert.ToInt, or prefer a different syntax like an actual if but in the end, somewhere, there will be your conditional.

int intValue = Convert.ToInt32(boolValue));

Use Convert.ToInt32(boolValue)

Despite the fact that nvoigt's answer is perfectly correct I can give you a few more examples JUST FOR FUN
NEVER! NEVER USE THIS CODE! IT IS PROVIDED JUST FOR FUN OR TO RESOLVE A DISPUTE WITH A (GOOD) FRIEND!)
At first method GetHashCode does the magic (as an implementation detail):
bool b = true;
int i = b.GetHashCode();
If you want some more esoteric approach.. hm.. you're welcome):
bool b = true;
int i = ~(b.ToString()[0] / 2) & 1;
REMEMBER! NEVER!

Related

Converting string to int (or something else), is there a prefered way?

Sometimes i wonder, when converting strings to other types, for example int32, is one way better than the other, or is it just a matter of taste?
Convert.ToInt32("123")
or
Int32.Parse("123")
or
Some other way?
Not considering the case if it's not a valid int in this question.
The Convert.ToInt32 is actually implemented the following way...
int.Parse(value, CultureInfo.CurrentCulture);
...which is the same as your stated alternative except it takes into account the culture settings. The int.Parse method is itself implemented the following way...
Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
...where Number is an internal class that you cannot call directly. The Number.ParseInt32 method is marked with the following attribute...
[MethodImpl(MethodImplOptions.InternalCall)]
...showing that it is implemented inside the CLR itself.
Main difference between Conver.ToInt32 and Int32.Parse is how the treat null strings. Convert.ToInt32 returns default value in this case:
public static int ToInt32(string value)
{
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
I don't like that. I think only "0" should be parsed to 0. This behavior initially was designed for Visual Basic programmers:
This is a set of conversion methods for programmers migrating from Visual Basic 6 to Visual Basic .NET that mirrored the behavior of the
existing Visual Basic 6 conversion methods. The assumption was that C#
programmers would be more comfortable with casting operators, whereas
Visual Basic had traditionally used conversion methods for type
conversion.
So, as non-VB programmer, I'd go with Int32.Parse and Int32.TryParse.
When converting from string to int I always use int.TryParse. Because you are not always sure you can convert a string to an int. Like this:
string temp="222";
int intValue;
if(int.TryParse(temp,out intValue))
{
//Something
}
As V4Vendetta suggested it is better to use TryParse to avoid exceptions related to converting.
int result = 0;
a = "3";
string b = "b";
string c = "2147483648"; //int32 max value + 1
int.TryParse(a, out result); // returns true result=3
int.TryParse(b, out result); // returns false result=0
int.TryParse(c, out result); // returns false result=0

Why would one use the |= operator on a boolean value in C#?

Example:
We found this is some vendor written code and we're trying to figure out why they'd do this.
bool tmp = false;
if (somecase)
tmp = true;
if (someOtherCase)
tmp |= true;
For no good reason at all. A boolean value |= true will always be true. This is someone trying to be fancy, or forgetting boolean logic =)
Change it to tmp = true;.
Perhaps one of the boolean literals used to be a variable, and they just didn't think to change the operator when they changed the operand. Obviously the logic is equivalent.
More likely, they were thinking that in the second case, they want to retain the result of evaluating the first "if" condition. Of course, that's false reasoning.
A simpler equivalent statement:
bool tmp = somecase | someOtherCase;
EDIT
As pickypg notes, this statement could be confusing, since most people don't expect | with boolean values, and many won't notice it, or won't think about the implications for side effects. The best way to be explicit (if indeed there are side effects) would be minitech's solution: just change the |= to =.
Or, if there are no side effects to the someOtherCase expression, use Jakub Konecki's solution : someCase || someOtherCase.
Interesting - that looks like it's doing the equivalent:
tmp = tmp | true;
Which will always set tmp to true.
foo |= true is a short version of foo = foo | true.
The actual code can be rewritten as
bool tmp = false;
tmp |= someCase;
tmp |= someOtherCase;
Or even better as
someCase || someOtherCase
Like the other op= operators, x |= y is equivalent (except for multiple-evaluation side effects) to x = x | y. This is a terse way of writing if (!x) x = y; or if (y) x = true;.
However, it doesn't make any sense to have a constant on the right-hand side.
x |= true is more straightforwardly written as x = true
x |= false leaves x unchanged.
why they'd do this.
Some possible explanations are:
It's a typo: They meant to write tmp = true; instead of tmp |= true;, but never noticed it because their program happened to work as expected.
The RHS was originally a variable, which was replaced with the constant true without otherwise changing the code.
tmp was originally a bitfield (for which |= makes more sense), which was later reduced to a single bit.
The ultimate result will be "If any of the cases is true, the result will be true." There is no reason that you have to use the operator though, since the || in an if would work just as well.
A clever compiler could avoid the assignment in this case, though it probably wouldn't as it shouldn't short-circuit a bitwise operation. In any event, it seems like a micro-optimization. In reality I suspect it's a hold-over pattern the author has from using bit flags (or s/he just doesn't understand how it works). It would be better as:
bool tmp = somecase || someOthercase;
(and then inline the temporary if you only use it once)
Note that, when using flags, it does make sense.
#define CONDITION_ONE 0x01
#define CONDITION_TWO 0x02
int temp = 0;
if (somecase) {
temp = CONDITION_ONE;
}
if (someOthercase) {
temp |= CONDITION_TWO;
}
for bools not so much
however for bitflags this can allow code like this:
int flags=0;
flags|=READ;
//flags|=UPDATE;
foo(arg,flags);
this allows some flags to be easily commented out (and makes the used flags a tad more readable IMO)
This is equivalent to
tmp = tmp | true;
EDIT:
Which is equal to
tmp = true;
I concur with the rest of the posters here...!
More information here
Its an expression using the |= assignment operator. Check MSDN

dynamic arithmetic operators

I was wondering if there is a way to implement next example :
string tmp = "+";
int ans1 = 4 tmp 5;
tmp = "+";
int ans2 = 4 tmp 5;
Thanks
You can do this at least:
MyOpType tmp = "+";
int ans1 = 4 & tmp & 5;
tmp = "+"; // Could be any operator implemented by MyOpType
int ans2 = 4 & tmp & 5;
By creating a class called MyOpType which have implicit operator overloading from string to it self. This would also have to operator overload & to return some operator type which miss a single argument.
However, I do not recommend doing such "hacks" because it is not clear what the code does. And furthermore, I'm sure there is a better way to do what you what to do. So if you explain the context then we might find a better solution :)
I guess something like Result("+", 4, 5) would be cleaner and easier to implement. This leads me to the question: Where do you get the operator from? users? If not, a better solution can surely be found. If you want some form of "dynamic interpretation" then .Net Expressions trees could be interesting.
In exact that syntax - NO. Using some other syntax (closer to C#) - maybe
This subject called by "expression", there are many sample about it. the best one here
Good luck

Do I understand this right? Comparing and assigning in one line of code?

Can someone tell me if I understand this right.
private void SetFontWeight(FontWeight weight)
{
boldButton.IsChecked = weight == FontWeights.Bold;
}
Like what is getting me is how everything is in one line. Like they are comparing and then assigning.
So is there like some order. Logically it seems like it would be like
boldButton.IsChecked = (weight == FontWeights.Bold);
Is that correct it first does comparison then assigns?
Or I guess the long way would be
if(weight == FontWeights.Bold)
{
boldButton.IsChecked = true;
}
else
{
boldButton.IsChecked = false;
}
I also find it kinda weird that they are comparing a struct(FontWeights) to a Class. I would have though it would be like
weight.IsBold == FontWeights.Bold
Yup, equality comparison has higher precedence than assignment. Assignment has basically the lowest precedence, so just about any other operators will be executed before assignment happens.
I'm pretty certain that it's equivalent to
boldButton.IsChecked = (weight == FontWeights.Bold);
This sort of thing was inherited from C (originally) and it has to use parentheses to force assignment first:
if ((x = getcode()) == BAD_CODE) ...
In terms of your misgivings over the comparison, this is just one of the wonderful things that become possible when you're allowed to override comparison operators.
In fact, some would argue that this example makes more sense since you shouldn't have to worry about whether it's the IsBold property that you have to compare. The clas should (and does) figure that out because you're comparing it in a "boldness" sort of way :-)
As far as my understanding is concerned, equality checks will be performed first. No matter you put brackets or not.
Sample code;
public boolean SampleFunction()
{
int a = 1;
int b = 2;
boolean c= false;
c= a==b;
return c;
}
This will first check if a is equal to b. So it will return boolean value and assign it to c.

Using nullable types in C#

I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:
bool isNull = (i == null);
or
bool isNull = !i.HasValue;
Also when assigning to a non-null type is this:
long? i = 1;
long j = (long)i;
better than:
long? i = 1;
long j = i.Value;
I would use this:
long? i = 1;
...some code...
long j = i ?? 0;
That means, if i is null, than 0 will be assigned.
Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay.
What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience.
Note that in terms of performance, both forms compile down to the same IL, ie:
int? i = 1;
bool isINull = i == null;
int j = (int)i;
Ends up like this after the C# compiler has got to it:
int? i = 1;
bool isINull = !i.HasValue;
int j = i.Value;
I would always use the (i==null) form. It expresses what you are doing.
WRT the second question, I think either form is fine. However I'd always check it against null first and take appropriate action - perhaps wrapping that check and action up in a helper method (often it just sets a default value).
I haven't used Nullable Types in practice, but for the second, I'd actually suggest using j.GetValueOrDefault(). The documentation suggests that the latter would actually throw an InvalidOperationException in the event of a null value. Depending on the internal implementation of the explict cast operator for long?, the former might, too. I'd stick with GetValueOrDefault and treat the null/default case appropriately.
I tend to use the first on both, because as it needs to be supported later in its life-cycle, these seem easier to understand what the intent of the original writer.
Opened up Reflector. HasValue is a lookup on a boolean flag which is set when the value is changed. So in terms of cycles a lookup is going to be faster then compare.
public Nullable(T value)
{
this.value = value;
this.hasValue = true;
}
private bool hasValue;
internal T value;
public bool HasValue
{
get
{
return this.hasValue;
}
}
They're both the same, but I would use the former version on both, since it's more common in the language: comparison to null and casting to a type.
I usually tend to lean towards the first option in both scenarios, since it's more 'primitive' oriented opposed to object oriented (which was really what we were going for), but it really doesn't matter that much

Categories

Resources