# Operators in C#

• Post author:
• Post category:csharp-category

# Operators in C#

Operators in C#: A symbol that tells the compiler to perform specific mathematical and logical operations is called an operator. C# has a rich collection of operators. C# has the following types of operators.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Operators

We will explain these operators one by one.

### Arithmetic Operators in C#

The table given below shows all the Arithmetical Operators supported by C#.

For example, we have two variables x=10 and y=2 then;

 Operators Category Description Example + Binary Perform addition of  operands x+y =12 – Binary Perform subtraction of the second operand from the first one x-y = 8 * Binary Perform Multiplication of operands x*y = 20 / Binary Divides the numerator by de-numerator x/y = 5 % Binary Modulus or Remainder Operator x%y = 0 ++ Unary Increase the value of an integer by one x++ = 11 – – Unary Decrease the value of an integer by one x– = 9

Binary Operands: Act on two operands

Unary Operands: Act on single Operands

Example:

Now we will demonstrate all arithmetic symbols with a working example.

```   using System;
namespace OperatorsInC#
{
class Program
{
static void Main(string[] args)
{
int x =15;
int y =5;
int z;
z=x+y;
Console.WriteLine("Value of z is {0}", c);
z=x-y;
Console.WriteLine("Value of z is {0}", z);
z=x*y;
Console.WriteLine("Value of z is {0}", z);
z=x/y;
Console.WriteLine("Value of z is {0}", z);
z=x%y;
Console.WriteLine("Value of z is {0}", z);
z=x++;
Console.WriteLine("Value of z is {0}", z);
z=x--;
Console.WriteLine("Value of z is {0}", z);
}
}
}```

Output:

Value of z is 20
Value of z is 10
Value of z is 75
Value of z is 3
Value of z is 0
Value of z is 16
Value of z is 14

### Relational Operators in C#

The relational operators are used to make Boolean comparisons. The following table shows all the relational operators.

Assume Variable x=10 and y=20

 Operator Category Description Example = = Binary Check the two operands if they are equal, if yes then true ( x= = y ) is false. != Binary Check the two operands if they are not equal, if yes then true ( x!= y ) is true. > Binary Check that if the left operand is greater than the right operand, if yes than true. ( x>y ) is false. < Binary Check that if the left operand is smaller than the right operand, if yes then true. ( x= Binary Check that if the left operand is greater or equal to the right operand if one condition satisfies then true. ( x>= y ) is false. <= Binary Check that if the left operand is smaller or equal to the right operand if one condition satisfies then true. ( x >= y ) is false

The relational operators are usually used in control statements. But for now, we’ll explain these with a working example. Don’t worry if you don’t understand the program right now. We’ll explain this program in our upcoming tutorials.

Example:

In the following example, we have used another method of Console class which is ReadLine(). This method simply reads the input given by the user on the console screen. Another new line of code we used is Convert.ToInt32().Convert is a class which contains many methods to convert one data type into another data type. ReadLine() method read-string type value so we have to convert it to our required data type.

```   using System;
namespace RelationalOperators
{
class program
{
int student1_age;
int student2_age;

//prompts the user for entering the age

Console.WriteLine("Enter the age of students:");

//read the value entered by user and then store in assigned variable

//Equal Operator

if (student1_age == student2_age )
{
Console.WriteLine("The age of both students is equal");
}

//Not eqaul operator

if (student1_age != student2_age )
{
Console.WriteLine("The age of both students are not equal");
}

//greater than operator

if (student1_age > student2_age)
{
Console.WriteLine("The student1 is elder than student2 ");
}

//smaller than operator

if (student1_age < student2_age )
{
Console.WriteLine("The student1 is younger than student2");
}

//greater or equal to operator

if (student1_age >=student2_age )
{
Console.WriteLine("The age of student1 is greater or equal to the age of student2 ");
}

//smaller or equal to operator

if (student1_age <=student2_age)
{
Console.WriteLine("The age of student1 is smaller or equal to the age of student2 ");
}
}
}```

### Logical Operators in C#

The logical operators have Boolean operands. In logical operators, we combine different Boolean operands to create a complex logical expression. The logical operators that are used in C# are shown in the table below. Assume that we have two Boolean type variables x=true and y=false then;

 Operator Description Example && It is called a logical and operator. If both operands are true then the condition is true otherwise false. (x&& y) is false. || It is called a logical OR operator. If both operands are false then the condition is false otherwise true. (x || y) is true. ! It is called logical NOT operator. It will reverse the condition. If the actual condition is true then it will make it false. It is a unary operator. !(x && y) is true

Example:

Let’s take an example of logical operators.

```   using System;
namespace OperatorsInC#
{
class Program
{
public static void Main(string[] args)
{

//AND operator
//if the left operands is false then AND operator skips the right operand
//and overall result is false

if((10<hourOfTheDay) && (hourOfTheDay<24))
{
Console.WriteLine("Hi-Ho,Hi-Ho,it's off to work we go.");
}

//OR Operator
//If one of the operands is true then overall result of OR operator is true

if( (hourOfTheDay>23) || (hourOfTheDay<0))
Console.WriteLine("The time you entered is invalid.");

//NOT operator
bool valid=false;
bool result=!valid;

//Displays result=True
Console.WriteLine("result={0}",result);

}
}
}
```

### Assignment Operators in C#

Assignment operators are used to assigning values to variables. The assignment operator evaluates the expression on the right side of the operator and assign the value to the left side expression on the left side of the operator. A list of assignment operators is shown in the table below. Assume that we have a variable x then;

 Operator Details Example = It is a simple assignment operator. Assign the right operand to the left operand. x=10 += Add and assignment operator. It adds the right operand is the left operand and assigns resulting value to the left operand. x +=10 is equal to x+10 -= Subtract and assignment operator. It subtracts the right operand from left operand and assigns resulting value to the left operand. Advertisement x -=10 is equal to   x-10 *= Multiply and assignment operator. It multiplies the right operand with left operand and assigns resulting value to the left operand. x *=10 is equal to   x*10 /= Divide and assignment operator. It divides the left operand with the right operand and assigns resulting value to the left operand. x /=10 is equal to   x/10 %= Modulus and assignment operator. It takes the modulus of the left operand concerning the right operand and assignment resulting value to left operand. x %=10 is equal to   x%10 <<= Left shift and assignment operator x <<=1 is equal to x<<1 >>= Right shift and assignment operator x >>=1 is equal to x>>1 &= Bitwise AND assignment operator x &=1 is equal to     x & 1 ^= Bitwise exclusive OR assignment Operator x ^=1 is equal to     x ^ 1 |= Bitwise inclusive OR assignment Operator x |=1 is equal to      x | 1

Example:

```   using System;
namespace OperatorsInC#
{
class Program
{
public static void Main(string[] args)
{
int x =32;
int z;
z=x;
Console.WriteLine("Line 1 - = Value of c = {0}", z);
z+=x;
Console.WriteLine("Line 2 - += Value of c = {0}", z);
z-=x;
Console.WriteLine("Line 3 - -= Value of c = {0}", z);
z*=x;
Console.WriteLine("Line 4 - *= Value of c = {0}", z);
z/=x;
Console.WriteLine("Line 5 - /= Value of c = {0}", z);
z=200;
z%=x;
Console.WriteLine("Line 6 - %= Value of c = {0}", z);
z<<=1;
Console.WriteLine("Line 7 - <<= Value of c = {0}", z);
z>>=1;
Console.WriteLine("Line 8 - >>= Value of c = {0}", z);
z&=1;
Console.WriteLine("Line 9 - &= Value of c = {0}", z);
z^=1;
Console.WriteLine("Line 10 - ^= Value of c = {0}", z);
z|=1;
Console.WriteLine("Line 11 - |= Value of c = {0}", z);
}
}
}
```

Output: ### Bitwise Operators in C#

Bitwise operators are also common to all programming languages. This is used to manipulate the values in binary format. Using a bitwise operator needs a complete understanding of binary operations. The data stored in the computer is in the form of binary digits (0 and 1). These digits are grouped together to form bytes, Kilobytes, Megabytes and etc. The following are the most used Bitwise operators.

• Binary AND operator (&)
• Binary OR operator ( | )
• Binary Exclusive OR operator ( ^ )
• Binary one’s complement operator ( ~ )
• Binary Right Shift Operator ( >> )
• Binary Left Shift Operator ( << )
1. Binary AND, OR and Exclusive OR operators

The bitwise AND, OR and Exclusive OR of two values would be the bit-by-bit comparison of bits in the first operand and second operand. The following example demonstrates the use of these operators.

```   byte and, or ,xor;
and= 12 & 7;
or= 12| 7;
xor= 12^7;
System.Console.WriteLine("and={0}\n or={1}\n xor={2}",and,or,xor);
```

Output: 1. Shift Operators

Sometimes you want to move the binary value to the right or left of a number. In executing a left shift, all bits in a number’s binary representation are shifted to the left by the number of locations specified by the operand on the right of the shift operator. Zeroes are then used to backfill the locations on the right side of the binary number. A right-shift operator does just about the same thing but in the opposite direction. However, if the number is a negative value of a signed type, the values used to backfill the left side of the binary number are ones and not zeroes. The shift operators are >> and <<, the right-shift and left-shift operators, respectively. Also, there are combined shift and assignment operators, <<= and >>=.

```   static void Main(string[] args)
{
//right-shift
int x;
x=(-7>> 2);
System.Console.WriteLine("x={0}",x);
//left-shift
x = (-7 << 2);
System.Console.WriteLine("x={0}", x);
}
```

Output: ### Misc. Operators in C#

There are some other operators in C#. These are given in the table below.

 Operators Details Example sizeof() Returns the size of data type sizeof(double),return 8 typeof() Returns the type of class typeof(console) & Returns the address of the variable &b; returns the address of memory of b ? : Conditional operator If Condition is true? Then value A: Otherwise, value B Is Checks that if an object is of a certain type If (the cow is Animal) As Cast without throwing an exception Object obj = new StringReader(“Hello”); StringReader r = obj as StringReader;

### Operator Precedence in C#

Operator precedence means in which order operators are evaluated if there are more than one operators.

 Category Operator Associativity Postfix () [] -> . ++ – – Left to right Unary + – ! ~ ++ – – (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + – Left to right Shift <<>> Left to right Relational <<= >>= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Type Conversion & Casting