Specialized C# Operators
In a previous post I went over some random C# operators. This article is a follow-up to that one, covering some more advanced C# operators and techniques. Specifically, the ?: operator, the ~ operator, |= operator, and the ^= operator.
We will start off with the conditional operator ?:. This operator is used to simplify an expression to test for a boolean value, and execute specific code that matches the value. Let’s start off with a code snippet that does not use the ?: operator.
1 2 3 4 5 6 7 | |
Instead we can use ?: to simplify that. We can refactor that into a new code snippet:
1 2 3 | |
In plain English the ?: operator reads as:
1 | |
Now we will move onto the ~ operator. This operator is used for a NOT bitwise operation, or better stated from MSDN:
The ~ operator performs a bitwise complement operation on its operand. Bitwise complement operators are predefined for
int,uint,long, andulong.Source: ~ Operator
A NOT bitwise operation is also known as a one’s compliment operation. It takes the binary of a variable or object, and flips each bit to a 0 if it was a 1, and to a 1 if it was a 0. The code below demonstrates the operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
As you can see, all of the bits are flipped to their opposite partner. This is could be useful if you are using C# to interact with a piece of hardware, and need to manipulate the bits of data that is exchanged with said hardware.
Next we have the |= operator. This operator performs a bitwise OR operation against a variable. So when compare two values, if one or both are true, then the result must be true. The following C# code shows an example of the OR operation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
Once again, this is useful for specific hardware signaling or situations where specific binary operations are needed.
Finally we have the ^= operator. This operator is another bitwise operator, specifically the exclusive OR (XOR). An XOR operation returns a true result if exactly one operand has a true value. If both compared values are true or both are false, XOR will yield a false result. This code snippet demonstrates how it works in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
Again, this is useful for things like hardware communication or data stream manipulation.
There are a ton more bitwise operations that C# can perform, all of which are detailed on MSDN