Operators in C#

Operators in C# with Examples

In this article, I am going to discuss Operators in C# with Examples. Please read our previous article, where we discussed Type Casting in C# with Examples. The Operators are the foundation of any programming language. Thus, the functionality of the C# language is incomplete without the use of operators. At the end of this article, you will understand what are Operators and when, and how to use them in C# Application with examples.

What are Operators in C#?

Operators in C# are symbols that are used to perform operations on operands. For example, consider the expression 2 + 3 = 5, here 2 and 3 are operands and + and = are called operators. So, the Operators in C# are used to manipulate the variables and values in a program.

Types of Operators in C#:

The Operators are classified based on the type of operations they perform on operand in C# language. They are as follows:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Unary Operators or
  7. Ternary Operator or Conditional Operator

In C#, the Operators can also be categorized based on the Number of Operands:

  1. Unary Operator: The Operator that takes one operand to perform the operation.
  2. Binary Operator: Then Operator that takes two operands to perform the operation.
  3. Ternary Operator: The Operator that takes three operands to perform the operation.

For a better understanding, please have a look at the below image.

Types of Operators in C#

Arithmetic Operators in C#

The Arithmetic Operators in C# are used to perform arithmetic/mathematical operations like addition, subtraction, multiplication, etc. on operands. The following Operators are falling in this category are:

Addition Operator (+):
The ‘+’ operator adds two operands. Adds the left operand with the right operand and returns the result. For example:
int a=10;
int b=5;
int c = a=b; //15

Subtraction Operator (-):
The ‘–‘ operator subtracts two operands. Subtracts the left operand and right operand and returns the result. For example:
int a=10;
int b=5;
int c = a-b; //5

Multiplication Operator (*):
The ‘*’ operator multiplies two operands. It multiplies the left and right operand and returns the result. For example:
int a=2;
int b=3;
int c=a*b; //6

Division Operator (/):
The ‘/’ operator divides the first operand by the second. Divides the left operand with the right operand and returns the result. For example:
int a=10;
int b=5;
int c=a/b; //0

Modulus Operator (%):
The ‘%’ operator returns the remainder when the first operand is divided by the second. Divides the left operand with the right operand and returns the remainder. For example:
int a=10;
int b=5;
int c=a%b; //2

Example to Understand Arithmetic Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int Result;
            int Num1 = 20, Num2 = 10;

            // Addition Operation
            Result = (Num1 + Num2);
            Console.WriteLine("Addition Operator: " + Result);

            // Subtraction Operation
            Result = (Num1 - Num2);
            Console.WriteLine("Subtraction Operator: " + Result);

            // Multiplication Operation
            Result = (Num1 * Num2);
            Console.WriteLine("Multiplication Operator: " + Result);

            // Division Operation
            Result = (Num1 / Num2);
            Console.WriteLine("Division Operator: " + Result);

            // Modulo Operation
            Result = (Num1 % Num2);
            Console.WriteLine("Modulo Operator: " + Result);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Arithmetic Operators in C#

Assignment Operators in C#:

The Assignment Operators in C# are used to assign a value to a variable. The left side operand of the assignment operator is a variable and the right-side operand of the assignment operator is a value.

The most important point that you need to keep in mind is that the value on the right side must be of the same data type as the variable on the left side else we will get a compile-time error. The different Types of Assignment Operators supported in the C# language are as follows:

Simple Assignment (=):

This operator Assign the right operand to the left operand. This operator is used to assign the value on the right-side operand to the variable on the left.
Example:
int a=10;
int b=20;
char ch = ‘a’;
a=a+4; //(a=10+4)
b=b-4; //(b=20-4)

Add Assignment (+=):

This operator is the combination of + and = operators. It is used to Add the left operand with the right operand and then assign it to the variable on the left.
Example:
int a=5;
int b=6;
a += b; //a=a+b; That means (a += b) can be written as (a = a + b)

Subtract Assignment (-=):

This operator is the combination of – and = operators. This operator is used to subtract the left operand from the right operand and then assign it to the variable on the left.
Example:
int a=10;
int b=5;
a -= b; //a=a-b; That means (a -= b) can be written as (a = a – b)

Multiply Assignment (*=):

This operator is the combination of * and = operators. This operator is used to multiply the left operand with the right operand and then assign it to the variable on the left.
Example:
int a=10;
int b=5;
a *= b; //a=a*b; That means (a *= b) can be written as (a = a * b)

Division Assignment (/=):

This operator is the combination of / and = operators. This operator is used to divide the left operand with the right operand and then assign it to a variable on the left.
Example:
int a=10;
int b=5;
a /= b; //a=a/b; That means (a /= b) can be written as (a = a / b)

Modulus Assignment (%=):

This operator is the combination of % and = operators. This operator is used to assign modulo of left operand with right operand and then assign it to the variable on the left.
Example:
int a=10;
int b=5;
a %= b; //a=a%b; That means (a %= b) can be written as (a = a % b)

Example to Understand Assignment Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize variable x using Simple Assignment Operator "="
            int x = 15;

            // it means x = x + 10
            x += 10;
            Console.WriteLine("Add Assignment Operator: " + x);

            // initialize variable x again
            x = 20;

            // it means x = x - 5
            x -= 5;
            Console.WriteLine("Subtract Assignment Operator: " + x);

            // initialize variable x again
            x = 15;

            // it means x = x * 5
            x *= 5;
            Console.WriteLine("Multiply Assignment Operator: " + x);

            // initialize variable x again
            x = 25;

            // it means x = x / 5
            x /= 5;
            Console.WriteLine("Division Assignment Operator: " + x);

            // initialize variable x again
            x = 25;

            // it means x = x % 5
            x %= 5;
            Console.WriteLine("Modulo Assignment Operator: " + x);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Assignment Operators in C#

Relational Operators in C#:

The Relational Operators in C# are also known as Comparison Operators. It determines the relationship between two operands and returns the Boolean results, i.e. true or false after the comparison. The Different Types of Relational Operators supported by C# are as follows.

Equal to (==):

This Operator is used to return true if the left-hand side is equal to the right-hand side. For example, 5==3 is evaluated to be false. So, this Equal to (==) operator will check whether the two given operands are equal or not. If equal returns true else returns false.

Not Equal to (!=):

This Operator is used to return true if the left-hand side operand is not equal to the right-hand side operand. For example, 5!=3 is evaluated to be true. So, this Not Equal to (!=) operator will check whether the two given operands are equal or not. If equal returns true else returns false.

Less than (<):

This Operator is used to return true if the left-hand side operand is less than the right-hand side operand. For example, 5<3 is evaluated to be false. So, this Less than (<) operator will check whether the first operand is lesser than the second operand or not. If so, returns true else returns false.

Less than or equal to (<=):

This Operator is used to return true if the left-hand side operand is less than or equal to the right-hand side operand. For example, 5<=5 is evaluated to be true. So. this Less than or equal to (<=) operator will check whether the first operand is lesser than or equal to the second operand. If so returns true else returns false.

Greater than (>):

This Operator is used to return true if the left-hand side operand is greater than the right-hand side operand. For example, 5>3 is evaluated to be true. So, this Greater than (>) operator will check whether the first operand is greater than the second operand. If so, returns true else return false.

Greater than or Equal to (>=):

This Operator is used to return true if the left-hand side operand is greater than or equal to the right-hand side operand. For example, 5>=5 is evaluated to be true. So, this Greater than or Equal to (>=) operator will check whether the first operand is greater than or equal to the second operand. If so, returns true else returns false.

Example to Understand Relational Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            bool Result;
            int Num1 = 5, Num2 = 10;

            // Equal to Operator
            Result = (Num1 == Num2);
            Console.WriteLine("Equal (=) to Operator: " + Result);

            // Greater than Operator
            Result = (Num1 > Num2);
            Console.WriteLine("Greater (<) than Operator: " + Result);

            // Less than Operator
            Result = (Num1 < Num2);
            Console.WriteLine("Less than (>) Operator: " + Result);

            // Greater than Equal to Operator
            Result = (Num1 >= Num2);
            Console.WriteLine("Greater than or Equal to (>=) Operator: " + Result);

            // Less than Equal to Operator
            Result = (Num1 <= Num2);
            Console.WriteLine("Lesser than or Equal to (<=) Operator: " + Result);

            // Not Equal To Operator
            Result = (Num1 != Num2);
            Console.WriteLine("Not Equal to (!=) Operator: " + Result);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Relational Operators in C#

Logical Operators in C#:

The Logical Operators in C# are mainly used in conditional statements and loops for evaluating a condition. They are basically used with binary numbers. The different types of Logical Operators supported in C# are as follows:

Logical OR (||):

This operator is used to return true if either of the Boolean expressions is true. For example, false || true is evaluated to be true. That means the Logical OR (||) operator returns true when one (or both) of the conditions in the expression is satisfied. Otherwise, it will return false. For example, a || b returns true if either a or b is true. Also, it returns true when both a and b are true.

Logical AND (&&):

This operator is used to return true if all the Boolean Expressions are true. For example, false && true is evaluated to be false. That means the Logical AND (&&) operator returns true when both the conditions in expression are satisfied. Otherwise, it will return false. For example, a && b returns true only when both a and b are true.

Logical NOT (!):

This operator is used to return true if the condition in expression is not satisfied. Otherwise, it will return false. For example, !a returns true if a is false.

Example to Understand Logical Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            bool x = true, y = false, z;

            //Logical AND operator
            z = x && y;
            Console.WriteLine("Logical AND Operator (&&) : " + z);

            //Logical OR operator
            z = x || y;
            Console.WriteLine("Logical OR Operator (||) : " + z);

            //Logical NOT operator
            z = !x;
            Console.WriteLine("Logical NOT Operator (!) : " + z);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Logical Operators in C#

Bitwise Operators in C#:

The Bitwise Operators in C# perform bit-by-bit processing. They can be used with any of the integer types. The different types of Bitwise Operators supported in C# are as follows.

Bitwise OR (|)

Bitwise OR operator is represented by |. This operator performs the bitwise OR operation on the corresponding bits of the two operands involved in the operation. If either of the bits is 1, it gives 1. If not, it gives 0.
For example,
int a=12, b=25;
int result = a|b; //29
How?
12 Binary Number: 00001100
25 Binary Number: 00011001
Bitwise OR operation between 12 and 25:
00001100
00011001
========
00011101 (it is 29 in decimal)
Note: If the operands are of type bool, the bitwise OR operation is equivalent to the logical OR operation between them.

Bitwise AND (&):

Bitwise OR operator is represented by &. This operator performs the bitwise AND operation on the corresponding bits of two operands involved in the operation. If both of the bits are 1, it gives 1. If either of the bits is not 1, it gives 0.
For example,
int a=12, b=25;
int result = a&b; //8
How?
12 Binary Number: 00001100
25 Binary Number: 00011001
Bitwise AND operation between 12 and 25:
00001100
00011001
========
00001000 (it is 8 in decimal)
Note: If the operands are of type bool, the bitwise AND operation is equivalent to the logical AND operation between them.

Bitwise XOR (^):

Bitwise OR operator is represented by ^. This operator performs a bitwise XOR operation on the corresponding bits of two operands. If the corresponding bits are different, it gives 1. If the corresponding bits are the same, it gives 0.
For example,
int a=12, b=25;
int result = a^b; //21
How?
12 Binary Number: 00001100
25 Binary Number: 00011001
Bitwise AND operation between 12 and 25:
00001100
00011001
========
00010101 (it is 21 in decimal)

Bitwise Complement (~):

The Bitwise Complement operator is represented by ~. It is a unary operator, i.e. operates on one operand. This operator inverts the bit pattern i.e. it makes every 1 to 0 and every 0 to 1.
For Example,
int a=26;
int result = ~a; //-27
How?
26 Binary Number: = 00011010
Bitwise Complement operation on 26:
~ 00011010 = 11100101 = 229 (In Decimal)
But we are getting -27 in the output. Why? It happens because the binary value 11100101 which we expect to be 229 is actually a 2’s complement representation of -27. Negative numbers in computers are represented in 2’s complement representation. For any integer n, 2’s complement of n will be -(n+1). The bitwise complement of 26 is 229 (in decimal) and the 2’s complement of 229 is -27. Hence the output is -27 instead of 229.

Bitwise Operators in C#

Example to Understand Bitwise Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 12, b = 25, Result;

            // Bitwise AND Operator
            Result = a & b;
            Console.WriteLine("Bitwise AND: " + Result);

            // Bitwise OR Operator
            Result = a | b;
            Console.WriteLine("Bitwise OR: " + Result);

            // Bitwise XOR Operator
            Result = a ^ b;
            Console.WriteLine("Bitwise XOR: " + Result);

            // Bitwise AND Operator
            Result = ~26;
            Console.WriteLine("Bitwise Complement: " + Result);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Bitwise Operators in C#

Unary Operators in C#:

The Unary Operators in C# need only one operand. They are used to increment, decrement, or negate a value. There are two types of Unary Operators. They are as follows:

  1. Increment operators (++): Example: (++x, x++)
  2. Decrement operators (–-): Example: (-–x, x–)
Increment Operator (++) in C# Language:

The Increment Operator (++) is a unary operator. It takes one value at a time. Again, it is classified into two types:

  1. Post-Increment Operator
  2. Pre-Increment Operator
Post Increment Operators:

The Post Increment Operators are the operators that are a suffix to its variable. It uses the value present inside the variable. It increments the value present inside the variable by 1 and updates it.
Syntax: Variable++;
Example: x++;

Pre-Increment Operators:

The Pre-Increment Operators are the operators which is a prefix to their variable. It increments the value present inside the variable by 1 and updates it then it uses the value present inside the variable.
Syntax: ++Variable;
Example: ++x;

Example to Understand Increment Operators in C# Language:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Post-Increment
            int x = 10;
            // Result1 is assigned 10 only,
            // x is not updated yet
            int Result1 = x++;
            //x becomes 11 now
            Console.WriteLine("x is {0} and Result1 is {1}", x, Result1);

            // Pre-Increment 
            int y = 10;
            int Result2 = ++y;
            //y and Result2 have same values = 11
            Console.WriteLine("y is {0} and Result2 is {1}", y, Result2);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Increment Operators in C# Language

Note: The ++ operator in C# is used to increment the value of an integer. When placed before the variable name called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.

Decrement Operators in C# Language:

The Decrement Operator (–) is a unary operator. It takes one value at a time. It is again classified into two types. They are as follows:

  1. Post Decrement Operator
  2. Pre-Decrement Operator
Post Decrement Operators:

The Post Decrement Operators are the operators that are a suffix to its variable. It uses the value present inside the variable. It decrements the value present inside the variable by 1 and updates it.
Syntax: Variable–;
Example: x–;

Pre-Decrement Operators:

The Pre-Decrement Operators are the operators that are a prefix to its variable. It decrements the value present inside the variable by 1 and updates it then it uses the value present inside the variable.
Syntax: –Variable;
Example: –x;

Example to understand Decrement Operators in C# Language:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Post-Decrement
            int x = 10;
            // Result1 is assigned 10 only,
            // x is not yet updated
            int Result1 = x--;
            //x becomes 9 now
            Console.WriteLine("x is {0} and Result1 is {1}", x, Result1);

            // Pre-Decrement 
            int y = 10;
            int Result2 = --y;
            //y and Result2 have same values i.e. 9
            Console.WriteLine("y is {0} and Result2 is {1}", y, Result2);

            Console.ReadKey();
        }
    }
}
Output:

Example to understand Decrement Operators in C# Language

Note: The — operator in C# is used to decrement the value of an integer. When placed before the variable name called pre-decrement operator), its value is decremented instantly. For example, –x. And when it is placed after the variable name called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–.

Ternary Operator in C#:

The Ternary Operator in C# is also known as the Conditional Operator. It is actually the shorthand of the if-else statement. It is called ternary because it has three operands or arguments. The first argument is a comparison argument, the second is the result of a true comparison, and the third is the result of a false comparison.

Syntax: Condition? first_expression : second_expression;

The above statement means that first, we need to evaluate the condition. If the condition is true the first_expression is executed and becomes the result and if the condition is false, the second_expression is executed and becomes the result.

Example to understand Ternary Operator in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 20, b = 10, c = 30, res;
            res = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
            Console.WriteLine("Max of three numbers = " + res);

            Console.ReadKey();
        }
    }
}

Output: Max of three numbers = 30

Shift Operator in C#:

The Shift Operator in C# is used when we want to perform logical bits operations, as opposed to mathematical operations. These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. Again, these operators are classified into two types. They are as follows:

Bitwise Left Shift Operator (<<) in C#:

The Bitwise left-shift operator is represented by <<. The Bitwise left-shift operator is used to shift a number to the left by a specified number of bits. Zeroes are added to the least significant bits. In decimal, it is equivalent to num * 2bits.
For Example, let’s say the number is 42. So, the binary equivalent of 42 is 101010. Bitwise Lift Shift operation on 42 are as follows:
42 << 1 = 84 (In binary 1010100)
42 << 2 = 168 (In binary 10101000)
42 << 4 = 672 (In binary 1010100000)

Bitwise Right Shift Operator (>>) in C#:

The Bitwise right shift operator is represented by >>. The Bitwise Right Shift Operator (>>) is used to shift a number to the right by a specified number of bits. The first operand is shifted to the right by the number of bits specified by the second operand. In decimal, it is equivalent to floor(num/2bits)
For Example, let’s say the number is 42. So, the binary equivalent of 42 is 101010. Bitwise Lift Shift operation on 42 are as follows:
42 >> 1 = 21 (In binary 010101)
42 >> 2 = 10 (In binary 001010)
42 >> 4 = 2 (In binary 000010)

Example to Understand Shift Operators in C#:
using System;
namespace OperatorsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 42;
            Console.WriteLine("{0}<<1 = {1}", number, number << 1);
            Console.WriteLine("{0}<<2 = {1}", number, number << 2);
            Console.WriteLine("{0}<<4 = {1}", number, number << 4);

            Console.WriteLine("{0}>>1 = {1}", number, number >> 1);
            Console.WriteLine("{0}>>2 = {1}", number, number >> 2);
            Console.WriteLine("{0}>>4 = {1}", number, number >> 4);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Shift Operators in C#

Operator Precedence and Associativity in C#

C# has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses. Precedence and Associative rules are used when dealing with equations involving more than one type of operator. In such cases, these rules determine which part of the equation to consider first as there can be many different valuations for the same equation.

Operator Precedence Order in C#:

When two operators share an operand, the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Operator Associativity in C#:

When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. For example, x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right-hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Some operators are not associative: for example, the expressions (x <= y <= z) and x++– are invalid.

In the next article, I am going to discuss Variables in C# with Examples. Here, in this article, I try to explain Operators in C# with Examples and I hope you enjoy this Operators in C# article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.