-2

I was wondering what is the difference between the two approaches, between |= and simply = although the same result. I don't know what is the difference

This is for educational purposes.

public int ValueA { get; set; }
public int ValueB { get; set; }
bool someBool { get; private set; }

#region using_|=
someBool |= ValueA >= ValueB;
#endregion

#region using_basic_=
someBool = ValueA >= ValueB;
#endregion
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
vnnbla
  • 1

1 Answers1

-1

I've never seen it, but it seems to work like the self incrementing += operator, except for booleans. So |= means, "set the variable to the logical result of the original value OR the right hand value".

So, in the code below, b becomes true because it was initially true, and that initial value was then compared to false. And true OR false = true.

var b = true;
b |= false;
Console.WriteLine(b); // true

But here, b is just simply set to true.

b = false;
Console.WriteLine(b);

And, as I suspected, there is also an &= operator.

pwilcox
  • 5,542
  • 1
  • 19
  • 31