Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "&=" in this C# code do?

Tags:

I came across some code that looks like this:

string someString;

...

bool someBoolean = true;
someBoolean &= someString.ToUpperInvariant().Equals("blah");

Why would I use the bitwise operator instead of "="?

like image 657
Matthew Steven Monkan Avatar asked Dec 29 '10 16:12

Matthew Steven Monkan


People also ask

What does the fox say Meaning?

Speaking of the meaning of the song, Vegard characterizes it as coming from "a genuine wonder of what the fox says, because we didn't know". Although interpreted by some commentators as a reference to the furry fandom, the brothers have stated they did not know about its existence when producing "The Fox".

What does the fox say for real?

One of the most common fox vocalizations is a raspy bark. Scientists believe foxes use this barking sound to identify themselves and communicate with other foxes. Another eerie fox vocalization is a type of high-pitched howl that's almost like a scream.

How can I find a song by the sound?

On your phone, touch and hold the Home button or say "Hey Google." Ask "What's this song?" Play a song or hum, whistle, or sing the melody of a song. Hum, whistle, or sing: Google Assistant will identify potential matches for the song.


1 Answers

It's not a bitwise operator when it's applied to boolean operators.

It's the same as:

someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");

You usually see the short-cut and operator &&, but the operator & is also an and operator when applied to booleans, only it doesn't do the short-cut bit.

You can use the && operator instead (but there is no &&= operator) to possibly save on some calculations. If the someBoolean contains false, the second operand will not be evaluated:

someBoolean = someBoolean && someString.ToUpperInvariant().Equals("blah");

In your special case, the variable is set to true on the line before, so the and operation is completely unneccesary. You can just evaluate the expression and assign to the variable. Also, instead of converting the string and then comparing, you should use a comparison that handles the way you want it compared:

bool someBoolean =
  "blah".Equals(someString, StringComparison.InvariantCultureIgnoreCase);
like image 181
Guffa Avatar answered Oct 14 '22 19:10

Guffa