# Operators in C#: Arithmetic, Assignment, logical, relational and bitwise

**Operators and Expressions in C#:**

Now that you are familiar with variable declaration and initialization, it’s time to find out what actions you can perform on them. For these purposes, the C# language has a whole set of operators, in particular, the assignment operator =, which we have already used. Writing operators in c# in a specific combination with variable and literal values (when used in conjunction with they are called operands), we can create expressions that are the basic building blocks of computer programs.

There are various operators in c#, ranging from the most basic to extremely complex that you are unlikely to meet anywhere except in mathematical applications. Simple operators in c# include all basic mathematical actions (for example, the + operator performs the addition of two operands), and complex operators in c# are designed to perform manipulations on a binary representation the content of the variable. There are also logical operators in c#, work with boolean values, and assignment operators like =.

In this article, we will focus on the mathematical operators in c# frames and the assignment operator, in which we begin to study Boolean logic in the context of control of the course program execution. All operators in c# can be roughly divided into three categories:

- Unary operators in c# that perform an action over a single operand.
- Binary operators in c# that perform an action over two operands.
- Ternary operators in c# that perform an action over three operands.

Most operators in c# fall into the binary category; there is also several unary operators and a single trinary one called conditional operator (a conditional operator is a logical operator, i.e. returns a boolean value;).

**Operators priority in c#:**

Each operator in c# belongs to a certain priority class, i.e. it has a defined priority. In an expression, the operators are processed in the order of their precedence, with operator higher priority should be evaluated first.

priority | Operators | importance | Associativity |

Primary | x.y
M(x) a[x] x++ x– new typeof checked unchecked |
Member access
Method call indexing Post increment Post decrement Object creation Type identification Overflow check Overflow check |
– |

Unary | +
– ! ~ ++x –x (Typ) x |
sign
sign Logical negation Bit complement Pre-increment Pre-decrement Typecast |
– |

Multiplicative | *
/ % |
multiplication
division Modulo |
L–R |

Additive | +
– |
addition
subtraction |
L–R |

shift | <<
>> |
Left shift
Right shift |
L–R |

Relation and type check | <
<= > >= is as |
smaller
less than or equal to greater greater or equal Type check Typecast |
L–R |

Equality | ==
!= |
equal
unequal |
L–R |

AND | &
& |
Logical AND
Bitwise AND operation |
L–R |

XOR | ^
^ |
Logical XOR
Bitwise XOR operation |
L–R |

OR | |
| |
Logical OR
Bitwise OR link |
L–R |

Conditional AND | && | Logical AND | L–R |

Conditional OR | || | Logical OR | L–R |

Condition | : ? | Conditional operator | R–L |

Assignment | =
*=, /=, %=, +=, –=, &=, ^=, |=, <<=, >>= |
Assignment
Compound assignment |
R–L |

As you can see from the table, the multiplicative operators *, / and % have a higher precedence than the + and —additive operators, so that the point-before-stroke rule is also sufficient.

**Associativity of the operators:**

If several operators with the same priority follow one another in an expression, they are assigned according to the Associativity or orientation processed.

The primary and unary operators have no associativity.

The conditional operator and assignment operators are evaluated from right to left.

All other operators are L-R associative.

**Operands:**

Regardless of the order in which the operator is evaluated, the operands in an expression become Start of evaluation always calculated from left to right. This is important when the operands have side effects produce!

Consider the following code:

int i = 1;

int res = ++ i + 2 * ++ i;

Because of the higher priority, the * operator is evaluated before the + operator. But this means not that its operands are also evaluated first. Then the expression would be 3 + 2 × 2 equals 7.

In fact, the operands are pre-evaluated from left to right, making the expression 2 + 2 × 3 equal to 8 is calculated.

**Side effects and other pitfalls:**

When building more complex expressions that contain multiple operators and values, you should definitely watch out for possible unexpected side effects.

Side effects always arise when an instruction implicitly triggers further instructions – for example, if you call a method in the expression on the right side of a statement installs:

y = test() * 3;

Such side effects are usually desired and used in a targeted manner. Inaccurate knowledge of the evaluation Of expressions, however, as well as “particularly clever”, elaborate expressions can be added quickly cause side effects to appear that the programmer neither wanted nor foreseen were.

**Method calls in expressions:**

The use of methods in expressions is fundamentally uncritical. Caution should be exercised, however, if the called method changes another variable of the expression:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Demo { int x = 0; public int F (int i) { int tmp = x; x = i; return tmp; } public int G() { int y; y = F(2) + x * 3 ; return y; } } |

Pay attention to the assignment

y = F(2) + x * 3;

The dangerous thing here is that method F() changes the field x, which also flows into the expression. Which value y is assigned therefore depends crucially on when the method F () is executed becomes. However, it was easy to misjudge the assessment of the evaluation sequence. A cursory analysis could reveal that because of the higher precedence of the * operator first x * 3 is calculated and then the result is added to the return value of F(). If x were to Beginning with 0, then y would also be 0. In fact, y is assigned the value 6! It is true that the * operator before the + Operator is evaluated, but before the operators are the operands, strictly from left to right, evaluated. For the above expression, F (2) is executed first, with the effect that x afterward contains the value 2, and the multiplication x * 3 is calculated as 2 * 3.

**Consecutive operators in c#:**

In C# it is easy to string several operators together:

j = n + ++ m;

j = n +++ m;

To understand how the compiler evaluates such expressions, you need to know how the Compiler expressions broken down into syntactic tokens (identifiers, operators, keywords). If whitespace characters have been set, it uses them to recognize the individual tokens. The first example j = n + ++ m; is interpreted in such a way that the value of m increased by 1 to the value of n is added. But how does it look if the programmer has not provided any spaces (which is not a good Programming style is)? If there are no spaces between the tokens, the compiler tries the limits to determine between the elements itself by reading from left to right as many characters as possible together. The expression j = n +++ m; is therefore interpreted as j = n ++ + m.

**Binary numerical extensions (doctorates):**

The binary operators have the peculiarity that they only accept two operands of the same type. The following operation should therefore not be allowed at all:

byte factorA = 2;

int factorB = 3;

int product = factorA * factorB;

Two operands of different types are passed to the * operator. Actually this is one Error, but the compiler ironed it out with its implicit conversions; H. he changes the Operands of the smaller type (here byte) are automatically converted to a value of the larger type (here int). This is known as numerical expansion.

The numerical extensions ensure that the programmer can use the binary operators numerical Can process values without worrying too much about the necessary type adjustment of the Having to make operands. However, it should be aware of the type adjustments taking place in the background awareness.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
short age = 12; // Correct, because the compiler automatically converts the int literal into a // converts short value age + = 1; // Correct, the int literal is automatically converted into a // converts short value age = age + 4; // Error! The operands are aligned (to int). // The + operator adds the int values and returns an int value // back. However, this cannot be done without an explicit cast // stored in the short variable. |

**Arithmetic operators in c#:**

There are five simple arithmetic operators in c#, two of which have both binary and unary forms. The table below lists all arithmetic (or mathematical) operators in c#, elementary examples of their use are given and shows the results of their work with simple numeric types (integers and floating-point numbers).

Operator | Value | Usage example in expression | Result |

+ | Binary | Var1 = var2 + var3; | The variable Var1 is assigned a value, which is the sum of the values variables var2 and var3 |

– | Binary | Var1 = var2 – var3; | The variable Var1 is assigned a value, the resulting subtraction the value of var3 from the value variable var2 |

* | Binary | Var1 = var2 * var3; | The variable Var1 is assigned a value, which is the result multiplying var2 and var3 |

/ | Binary | Var1 = var2 / var3; | The variable var1 is assigned a value, which is the result of division variable var2 to variable var3 |

% | Binary | Var1 = var2 % var3; | The variable var1 is assigned a value, which is the remainder of the division variable var2 to variable var3 |

+ | Unary | Var1= + var2; | Variable var1 is assigned value variable var2 |

– | Unary | Var1= – var2; | The variable var1 is assigned a value variable var 2 multiplied by -1 |

Here are examples using simple numeric types, since the results obtained by dealing with other simple types may be unclear. What would you like to get when you add two boolean variables? We will not actually get anything, since the compiler will not allow use the + operator (as well as any other mathematical operators) with variables of type bool.

Adding char variables also looks somewhat confusing. If you remember, char variables are actually stored as numbers, so the addition of two char variables is also will be a number (of type int, to be precise). Such an action is an example of implicit type conversion, which we will talk about in more detail; we will also pay some attention to explicit type conversion since it is applicable when var1, var2, and var3 are of different types.

It should be noted that the binary operator + also makes sense when it used with variables of type string. In this case, the previous table should be supplemented with the following:

Operator | Value | Usage example in expression | Result |

+ | Binary | Var1 = var2 + var3; | The variable var1 is assigned a value, which is the result concatenation of two strings stored in variables var2 and var3 |

No other mathematical operators in c# can be applied to strings. The other two operators that we need to consider are the operators increase (increment) and decrease (decrement), each of which is unary operator and can be used in one of two ways: either immediately before or immediately after the operand. Let’s see the result that are obtained in the case of simple expressions, and then we will discuss them.

Operator | Value | Usage example in expression | Result |

++ (prefix operator) | Unary | Var1 = ++ var2; | Variable var1 is assigned a value variable var2+1. Variable var2 increases by one |

— (prefix operator) | Unary | Var1 = — var2; | Variable Var1 is assigned a value variable var2-1. Var2 variable decreases by one |

++ (postfix operator) | Unary | Var1 = var2 ++; | Variable var1 is assigned value variable var2. Variable var2 increases by one |

— (postfix operator) | Unary | Var1 = var2 –; | Variable var1 is assigned value variable var2. Variable var2 decreases by one |

These operators in c# always change the value stored in the corresponding next operand. The + + operator always increases the value of its operand by 1, and the operator decreases it by 1. The difference lies in the result which is written to the var1 variable since the location of the statement determines the order in which actions are performed. When either of these two operators in c# placed before the operand, it is performed before any other computation. Placing either of these two operators after the operand results in the operator is executed after all other calculations for the given expressions.

All that has been said deserves another example. Consider the following code:

1 2 3 |
Int var1, var2=5, var3=6; Var1 = var2 ++ * -- var3; |

Question: what value will be assigned to var1 variable? Before the expression starts evaluating, the operator – located before variable var3, which will change its value from 6 to 5. We can ignore the ++ operator behind var2 as it is not will have no effect as long as the evaluation of this expression will not be completed, so the result of multiplying 5 by 5 will be written to var1, those. 25. These simple unary operators turn out to be extremely handy for very many situations. In fact, they are just shorthand writing expressions like:

Var1 = var1 + 1;

It turns out that such expressions are very widespread, in particular, when organizing loops. So now let’s look at how you can use math technical operators in c#, and at the same time we will get acquainted with two more useful concepts.

**Division and Modulo:**

When using the operators for division and modulo calculation, note that the functionality of these operators is defined differently for integers and floating point numbers.

**Use with integers**

When dividing two integer values, the / operator returns the integer part of the division:

int x = 7/4; // x equals 1

int y = 8/4; // y equals 2

int z = 9/4; // z equals 2

When dividing two integer values modulo, the% operator returns the remainder of the division:

int div, mod;

div = 7/4; // 1

mod = 7% 4; // 3

**Use with floating-point numbers**

When dividing two floating-point values, the / operator returns the full result of the division (with

Fractional part):

double x = 7/4; // x is 1.75

Modulo division is less common for floating-point numbers because there is no “remainder of Division “ there. Even so, the modulo operator is also defined for floating-point types in C#. He leads one Integer division and returns the remainder. In principle, it works in the same way as the modulo Operator for integer numbers, but can also process floating-point operands and then returns also return floating-point numbers as a result:

double x = 7.8% 2; // x equals 1.8

**Example: Performing arithmetic or mathematical operations on variables:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MathOperators { class Program { static void Main(string[] args) { double firstNumber, secondNumber; string userName; Console.WriteLine("Enter your name:"); userName = Console.ReadLine(); Console.WriteLine("Welcome {0} !", userName); Console.WriteLine("Now give me a number:") ; firstNumber = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Now give me another number:") ; secondNumber = Convert.ToDouble(Console.ReadLine()); Console.WriteLine ( "The sum of {0} and {1} is {2}.", firstNumber, secondNumber, firstNumber + secondNumber); Console.WriteLine("The result of subtracting {0} from {1} is {2}.", secondNumber, firstNumber, firstNumber - secondNumber); Console.WriteLine("The product of {0} and {1} is {2}.", firstNumber, secondNumber, firstNumber * secondNumber); Console.WriteLine("The result of dividing {0} by {1} is {2}.", firstNumber, secondNumber, firstNumber / secondNumber); Console.WriteLine("The remainder after dividing {0} by {1} is {2}.", firstNumber, secondNumber, firstNumber % secondNumber); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } } |

output:

**How it works:**

This program not only demonstrates the use of mathematical operators in c#, but it also introduces two important concepts with which we will regularly found in training examples:

- User input
- Type conversion

For user input, the syntax is used, similar to the syntax of the console.writeLine() command you have already encountered. IN THIS CASE, the Console.ReadLine () command is used. This command displays an input prompt that fits to a variable of type string:

**string userName;**

**Console.WriteLine (“Enter your name:”);**

**userName = Console.ReadLine ();**

**Console, WriteLine (“Welcome {0} ! “, userName);**

This code displays the contents of the userName variable to the screen.

In this example, we also read two input numbers. Here everything turns out to be somewhat more complicated, since the Console.ReadLine command about generates a string, but we need numbers. This introduces the concept of transformation types. but first, let’s look at the code used in the example. First, we declare two variables in which we are going to store the input admissible numbers:

**double firstNumber, secondNumber;**

Then we set the prompt and apply with console.ReadLine about to the resulting line, the convert.ToDouble() command, which allows you to convert strings to double type. The resulting value is assigned to the first declared by us Variables – firstNumber:

**Console.WriteLine(“Now give me a number:”) ;**

**firstNumber = Convert.ToDouble(Console.ReadLine());**

This syntax is very simple, so it shouldn’t surprise you that many other types of conversions are done in a similar way. Further in the program, the second number is obtained in the same way:

**Console.WriteLine(“Now give me another number:”);**

**secondNumber = Convert.ToDouble(Console.ReadLine() );**

After that, the results of addition, subtraction, multiplication and division are displayed. two entered numbers, as well as the remainder of the division of these two numbers, obtained using the modulus operator (%):

**Console.WriteLine(“The sum of {0} and {1} is {2}.”, firstNumber,**

**secondNumber, firstNumber + secondNumber);**

**Console.WriteLine(“The result of subtracting {0} from {1} is {2}.”,**

**secondNumber, firstNumber, firstNumber – secondNumber);**

**Console.WriteLine(“The product of {0} and {1} is {2}.”, firstNumber,**

**secondNumber, firstNumber * secondNumber);**

**Console.WriteLine(“The result of dividing {0} by {1} is {2}.”, firstNumber,**

**secondNumber, firstNumber / secondNumber);**

**Console.WriteLine(“The remainder after dividing {0} by {1} is {2}.”,**

**firstNumber, secondNumber, firstNumber % secondNumber);**

Note that as parameters to the console.writeLine() statement we use expressions like firstNumber + secondNumber, avoiding the stage of assigning the values of these expressions to intermediate variables:

**Console.WriteLine(“The sum of {0} and {1} is {2}.”, firstNumber,**

**secondNumber, firetNumber + secondNumber) ;**

Using this syntax makes your code readable and reduces the number of lines.

**Increment and decrement operators in c#:**

We speak of increment or decrement when the value of variable increases or decreases by 1 shall be. The operators ++ and -, which can be placed before or after the respective variable, represent a shortened syntax for this. They are mostly used to implement counter variables or used to increase or decrease loop variables:

1 2 3 4 5 |
for (i = 0; i <10; ++ i) { } |

Both the increment and the decrement operator can be in prefix or postfix notation be used, i.e. the operator can be placed before or after its operand.

**++ x (prefix)**

**x ++ (Postfix)**

There is an important semantic difference between prefix and postfix, but it is only in Expressions shows where the value of the operand is processed further, for example in expressions with further operators or method calls:

**y = ++ x;**

**Method (x ++);**

- While the prefix operator increments (decrements) its operand and the new value returns to the surrounding expression,
- the postfix operator delivers the temporarily stored after incrementation (decrementation) old value of the operand to the surrounding expressions.

**x–;**

**for (i = 0; i <10; ++ i)**

Basically, the prefix operator works faster and conserves resources because it does not use the old value of the Must cache operands.

**Assignment operators in c#:**

Until now, we have used the simple assignment operator =, and it may seem surprising to someone that there are any other assignment operators in c#. However, they do exist and, it seems even more amazing, turn out to be quite useful!

All other assignment operators work similarly to the = operator. Just like the operator =, the result of their execution is the assignment of distribution of the left variable of the value calculated by the operators and operands located on the right side. Let’s present these operators and an explanation of their work in below table:

Operator | Value | Usage example in the expression | Result |

= | Binary | Var1 = var2; | The variable Var1 is assigned a value variable var2 |

+= | Binary | Var1 + = var2; | The variable var1 is assigned a value, which is the amount variables var1 and var2 |

-= | Binary | Var1 – = var2; | The variable var1 is assigned a value, which is the difference obtained by subtracting variable var2 from variable var1 |

*= | Binary | Var1 * = var2; | The variable var1 is assigned a value, which is a work variables var1 and var2 |

/= | Binary | Var1 / = var2; | The variable var1 is assigned a value, fission variable var1 to variable var2 |

%= | Binary | Var1 % = var2; | The variable var1 is assigned a value, remainder variable var1 to variable var2 |

As you may have noticed, the result of using additional operators The assignment moat is the involvement of the var1 variable in calculations, i.e. the code like:

**Var1 += Var2;**

results in exactly the same result as the code:

**var1 = var1 + var2;**

*Note that the + = operator can be used with strings, just like the + operator.*

Using these operators, especially when dealing with long names belt, allows you to make the program much more readable.

**The relational or Comparison operators in c#:**

A condition is an expression that can be true or false. In that section presents a simplified version of the C# if the command that allows an application to make a decision depending on the condition. For example, the condition “assessment greater than or equal to 601 > determines whether the student has reached the required number of points. If the condition in the if the command is true, then the body of the If command is executed. If the condition is false, then the body is not met. We’ll look at a specific example shortly.

Conditions in if commands can be constructed using check operators equality (== and! =) and comparison operators (>, <,> =, and <=) listed in the below table. The equality operators (== and! =) Have the same precedence; operators comparisons (>, <,> = and <=) also have the same precedence, but higher, than the equality operators. Operators are applied from left to right.

operator | importance | Example (for i equals 3) |

== | Equal | (i == 1) // false |

!= | Unequal | (i != 1) // true |

< | Less than | (i < 1) // false |

<= | Less than or equal to | (i <= 1)) // false |

> | Greater than | (i > 3) // false |

>= | Greater or equal | (i >= 3) // true |

The relational (comparative) operators in c# are used to make comparisons between two operands, including the Expressions can be carried out. The result of this operation is always a Boolean value (corresponds to true or false). Expressions that contain comparative operators are often used as control conditions used in loops and statements.

1 2 3 4 5 6 7 |
if (x < 10) { // ... } |

*Note: The == and! = Operators can compare any operator; the rest of the relational operators only compare numeric operands and operands of class types for which the operator concerned has been overloaded*

**Example: Comparing integers values using if statements, and check for equality and comparison:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Comparison { class Program { // The Main method starts executing the C# application static void Main(string[] args) { int number1; // Declare the first number to compare int number2; // Declare the second number to compare // Request and enter the first number Console.Write("Enter first integer:"); number1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter second integer: "); number2 = Convert.ToInt32(Console.ReadLine()); if (number1 == number2) Console.WriteLine("{0}=={1}", number1, number2); if ( number1 != number2) Console.WriteLine( "{0} != {1}", number1, number2 ); if ( number1 < number2) Console.WriteLine( "{0} < {1}", number1, number2 ); if ( number1 > number2) Console.WriteLine( "{0} > {1}", number1, number2 ); if ( number1 <= number2) Console.WriteLine( "{0} <= {1}", number1, number2 ); if ( number1 >= number2) Console.WriteLine( "{0} >= {1}", number1, number2 ); Console.ReadKey(); } } } |

output:

**The logical operators in c#:**

C# knows six operators for performing logical AND, OR, and NOT operations. At The logical AND and OR operators are linked to the logical value of the operands, the logical one NOT operator converts the logical value of its operand into the opposite. The operands must be Boolean values or expressions themselves. The result of a logical connection is again a boolean truth value.

operator | task | Example |

&&, & | Logical AND | (i > 1 && i < 10) |

||, | | Logical OR | (i < 1 || n > 10) |

^ | Logical XOR (exclusive or) | (i < 1 ^ n > 10) |

! | Logical NOT | !(i == 0) |

**Logical operator terminology:**

Under the concept of logical operators in C# summarizes those binary operators that consist of form their operands new values according to the laws of Boolean logic. These would be:

**The Boolean operators &, | and**^: which creates a new truth value by combining two truth values (i.e. bool operands) produce.**The conditional operators &&, ||:**which also link truth values (bool operands), but the evaluation of the second Save operands if the result has already been determined after evaluating the first operand.**The bitwise operators &, | and ^:**which the bits (zeros and ones) of their scalar operands (integer values) to a new integer Link value.

For once, we will not follow this very technical classification. Instead, subdivide we use the operators according to their functionality in

- logical operators that generate new bool values from bool operands (these would be the Boolean Operators, the conditional operators, and the logical NOT)
- bitwise operators that manipulate scalar operands bitwise.

**Logical AND (&&, &) operators in c#:**

A logical AND operation is carried out using the && operators in c#. The result of the link has the value true only if both operands have the value true. The following truth table shows you the possible combinations.

1st operand | 2nd operand | Result |

True | True | True |

True | False | False |

False | True | False |

False | False | False |

Using the logical AND link and an if condition, you can, for example, check whether the value of a variable is between 10 and 100:

if ((x> 10) && (x <100))

The && operators in c# is only evaluated from left to right until the result is known. If the the left operand already returns the value false, the evaluation is aborted. You can force the evaluation of the second operand by using the logical operator &:

if ((x> 10) & (x <100))

**Logical OR (||, |) operators in c#:**

The logical OR operators in c# combine their operands in such a way that the result of the combination has the value as true if at least one of the operands has the value true. The following truth table shows you the possible combinations.

1st operand | 2nd operand | Result |

True | True | True |

True | False | True |

False | True | True |

False | False | False |

With the help of the logical OR link and an if-condition you can check, for example, whether the value of a variable is less than 10 or greater than 100:

if ((x <10) || (x> 100))

Like the && operator, the || operator is only evaluated until the result is known. If you want both operands to always be evaluated, use the | operators in c#.

**Logical XOR (^) operators in c#:**

The logical XOR operator combines its operands so that the result of the combination has the value that has true if exactly one of the operands has the value true. The following truth table shows you the possible combinations.

1st operand | 2nd operand | Result |

True | True | False |

True | False | True |

False | True | True |

False | False | False |

**Logical NOT (!) operators in c#:**

The logical NOT operator reverses the truth value of its logical operand into the opposite:

1 2 3 4 5 6 7 8 9 10 11 |
bool status = false; if (!status) { Console.WriteLine("status: "+ status); } |

**Bitwise operators in c#:**

operator |
task |
Example |

& | Bitwise AND operation | ‘a’ & 223 |

| | Bitwise OR link | ‘A’ | 0x20 |

^ | Bitwise XOR (exclusive OR) | var1 ^ 0x0 |

~ | Bitwise complement | ~var1 |

>> | Right shift | i >> 2 |

<< | Left shift | j << 3 |

This group of operators in c# is especially important for system-level programming. She allows scalar values (integers) to be manipulated on the bit level.

1 2 3 4 5 |
// multiplication by 2 int smallNumber = 3; int res = smallNumber << 1; // res becomes 3 * 21 = 6 |

**2’s complement:**

Variables of integer types have the advantage that their values can be found in a simple way, namely according to the 2’s complement, are coded. In mathematical terms, the 2’s complement corresponds to the following figure:

Positive numbers start with a 0. The remaining bits correspond to the number in the binary system:

1 2 3 4 5 6 7 8 9 |
0000 0000 0000 0000 0000 0000 0000 0000 // equals 0 0000 0000 0000 0000 0000 0000 0000 0001 // equals 1 0000 0000 0000 0000 0000 0000 0000 0010 // equals 2 ... 0111 1111 1111 1111 1111 1111 1111 1111 // equals 2,147,483,647 |

Negative numbers start with a 1. The remaining bits are read as a binary number and reduced by 2^{n}, result in the corresponding number in the decimal system:

1111 1111 1111 1111 1111 1111 1111 1111 // equals -1 (2,147,483,647 – 2^{31})

1111 1111 1111 1111 1111 1111 1111 1110 // equals -2 (2,147,483,646 – 2^{31})

…

1000 0000 0000 0000 0000 0000 0000 0010 // equals -2,147,483,646 (2 – 2^{31})

1000 0000 0000 0000 0000 0000 0000 0001 // equals -2,147,483,647 (2 – 2^{31})

1000 0000 0000 0000 0000 0000 0000 0000 // equals -2,147,483,648 (2 – 2^{31})

**&, & = (bitwise AND) operators in c#:**

The operator matches its operands according to the rules of numerical extensions (see section “Side Effects and Other Pitfalls!” Earlier in this article) together so that they have the same bit length. Then it goes through the bits of the two operands. Whenever for one Bit position in both operands the respective bit is set to 1, the corresponding bit in the Result value set to 1. Otherwise, the result bit is set to 0.

1 2 3 4 5 6 7 |
0110 0001 & 1101 1111 ---------------- 0100 0001 |

This operator can be used to specifically delete bits.

1 2 3 4 5 |
int i = 0xFF; // i = 255 i & = 0xF0; // sets all bits except bits 5 to 8 to 0 // i = 240 |

**|, | = (bitwise OR) operators in c#:**

The operator matches its operands according to the rules of numerical extensions (see section “Side Effects and Other Pitfalls!” Earlier in this article) together so that they have the same bit length. Then it goes through the bits of the two operands. Whenever for oneBit position in one of the operands the respective bit is set to 1, the corresponding bit is also set in the Result value set to 1. Otherwise, the result bit is set to 0.

1 2 3 4 5 6 7 |
0110 0001 | 1101 1111 -------------- 1111 1111 |

This operator can be used to specifically set additional bits.

1 2 3 4 5 6 7 |
int i = 0xFF; // i = 255 i & = 0xF0; // sets all bits except bits 5 to 8 to 0 i | = 0xF; // sets the first 4 bits to 1 // i again equal to 255 |

**^, ^ = (bitwise XOR) operators in c#:**

The operator matches its operands according to the rules of numerical extensions (see section “Side Effects and Other Pitfalls!” Earlier in this article) together so that they have the same bit length. Then it goes through the bits of the two operands. Whenever for one Bit position if the respective bit is set to 1 in exactly one of the operands, the corresponding bit is also set Bit in the result value set to 1. Otherwise, the result bit is set to 0.

1 2 3 4 5 6 7 |
0110 0001 ^ 1101 1111 ---------------- 1011 1110 |

This operator can be used to switch bits (set bits are deleted and vice versa).

1 2 3 4 5 |
int i = 0x8; // i = 8 i ^ = 0xB; // 0xB = 11 -> clears the 4th bit // sets bits 1 and 2 |

**~ (bitwise complement) operator in c#:**

The operator goes through the bits of the operand and inverts them. Whenever for a bit position in theOperand the respective bit is set to 1, the corresponding bit in the result value is set to 0 and vice versa.

1 2 3 4 5 |
~ 0110 0001 ----------------- 1001 1110 |

**<< (left shift) operator in c#:**

The left shift operator copies the bits of the first operand into the result value however moved to the left by as many positions as the second operand specifies. The ones arising on the right Spaces are filled with 0:

int i = 3;
i << = 2; |
int value | Bit pattern (8 bit) |

Before postponement | 3 | 0000 0011 |

After postponement | 12 | 0000 1100 |

Each left shift by one position corresponds to a multiplication by 2. A left shift by n places therefore corresponds to a multiplication by 2^{n}. Negative shifts are not allowed. Shifts by more positions than the left operand Positions are not possible (shifting an int value by 34 positions is equal to the shift by 34% 32 equals 2 positions). The sign is not retained, i.e. that is, it becomes through the advancing Bit overwritten.

**>> (right shift) operator in c#:**

The right shift operator copies the bits of the first operand into the result value however moved to the right by as many positions as the second operand specifies. The ones emerging on the left For signed integer types, spaces are made with copies of the most significant bit (Sign bit) padded with 0 for uint or ulong.

int i = 3;
i >> = 2; |
int value | Bit pattern (only 8 bit) |

Before postponement | 3 | 0000 1100 |

After postponement | 12 | 0000 0011 |

Each right shift by one position corresponds to a division by 2. A right shift by n Digits, therefore, corresponds to division by 2^{n}. Negative shifts are not allowed. Shifts by more positions than the left operand Positions are not possible (shifting an int value by 34 positions is equal to the shift by 34% 32 equals 2 positions). The sign is retained.

**Programming Examples**:

**How to use simple Assignment operators in C#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AssignmentOperator { class Program { static void Main(string[] args) { int var1, var2; // Assigning a constant to variable var1 = 30; Console.WriteLine("First Number = {0}", var1); // Assigning a variable to another variable var2 = var1; Console.WriteLine("Second Number = {0}", var2); Console.ReadKey(); } } } |

output:

**How to use simple Relational operators in c#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RelationalOperator { class Program { static void Main(string[] args) { bool result; int var1 = 30, var2 = 50; result = (var1 == var2); Console.WriteLine("{0} == {1} returns {2}", var1, var2, result); result = (var1 > var2); Console.WriteLine("{0} > {1} returns {2}", var1, var2, result); result = (var1 < var2); Console.WriteLine("{0} < {1} returns {2}", var1, var2, result); result = (var1 >= var2); Console.WriteLine("{0} >= {1} returns {2}", var1, var2, result); result = (var1 <= var2); Console.WriteLine("{0} <= {1} returns {2}", var1, var2, result); result = (var1 != var2); Console.WriteLine("{0} != {1} returns {2}", var1, var2, result); Console.ReadKey(); } } } |

output:

**How to use simple Logical operators in c#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace logicalOperator { class Program { static void Main(string[] args) { bool result; int var1 = 50, var2 = 90; // OR operator result = (var1 == var2) || (var1 > 5); Console.WriteLine(result); // AND operator result = (var1 == var2) && (var1 > 5); Console.WriteLine(result); Console.ReadKey(); } } } |

output:

**How to use simple unary operators in c#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace unaryOperator { class Program { static void Main(string[] args) { int var = 10, result; bool flag = true; result = +var; Console.WriteLine("+variabe = " + result); result = -var; Console.WriteLine("-variabe = " + result); result = ++var; Console.WriteLine("++variabe = " + result); result = --var; Console.WriteLine("--variabe = " + result); Console.WriteLine("!flag = " + (!flag)); Console.ReadKey(); } } } |

output:

**How to use simple postfix and prefix increment operators in c#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace postAndPre { class Program { static void Main(string[] args) { int var = 50; Console.WriteLine((var++)); Console.WriteLine((var)); Console.WriteLine((++var)); Console.WriteLine((var)); Console.ReadKey(); } } } |

output:

**How to use simple ternary operators in C#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ternaryOperator { class Program { static void Main(string[] args) { int number; Console.WriteLine("Now give me a number:"); number = Convert.ToInt16(Console.ReadLine()); string result; result = (number % 2 == 0) ? "Even Number" : "Odd Number"; Console.WriteLine("{0} is {1}", number, result); Console.ReadKey(); } } } |

output:

**how to use simple bitwise operators in c#:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace bitwiseOperator { class Program { static void Main(string[] args) { int var1 = 40; int var2 = 60; int result; result = ~var1; Console.WriteLine("~{0} = {1}", var1, result); result = var1 & var2; Console.WriteLine("{0} & {1} = {2}", var1, var2, result); result = var1 | var2; Console.WriteLine("{0} | {1} = {2}", var1, var2, result); result = var1 ^ var2; Console.WriteLine("{0} ^ {1} = {2}", var1, var2, result); result = var1 << 2; Console.WriteLine("{0} << 2 = {1}", var1, result); result = var1 >> 2; Console.WriteLine("{0} >> 2 = {1}", var1, result); Console.ReadKey(); } } } |

output: