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 "="?
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);
It's the equivalent of += for the & operator.
someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");
which, in this case, before someBoolean is true, means
someBoolean = someString.ToUpperInvariant().Equals("blah");
It is short for:
someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah");
See MSDN (&= operator).
It is the short form of this:
someBoolean = someBoolean & someString.ToUpperInvariant().Equals("blah")
As Guffa pointed, there IS a difference between & and &&. I would not say you can, but rather you SHOULD use && instead of & : & makes your code geeker, but && makes your code more readable... and more performant. The following shows how :
class Program
{
static void Main(string[] args)
{
Stopwatch Chrono = Stopwatch.StartNew();
if (false & Verifier())
Console.WriteLine("OK");
Chrono.Stop();
Console.WriteLine(Chrono.Elapsed);
Chrono.Restart();
if (false && Verifier())
Console.WriteLine("OK");
Chrono.Stop();
Console.WriteLine(Chrono.Elapsed);
}
public static bool Verifier()
{
// Long test
Thread.Sleep(2000);
return true;
}
}
来源:https://stackoverflow.com/questions/4556027/what-does-the-in-this-c-sharp-code-do